GetObjectMetadata() public méthode

The HEAD operation retrieves metadata from an object without returning the object itself. This operation is useful if you're only interested in an object's metadata. To use HEAD, you must have READ access to the object.
public GetObjectMetadata ( GetObjectMetadataRequest request ) : GetObjectMetadataResponse
request GetObjectMetadataRequest Container for the necessary parameters to execute the GetObjectMetadata service method.
Résultat GetObjectMetadataResponse
Exemple #1
0
 public bool InstanceExists(Guid instanceKey)
 {
     try
     {
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObjectMetadata(new GetObjectMetadataRequest()
             {
                 BucketName = Context.BucketName,
                 Key = string.Format("{0}/{1}/{2}", STR_INSTANCES_CONTAINER_PATH, instanceKey.ToString("N"), STR_INFO_FILE_NAME),
             })) { return true; }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return false;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed getting instance with key \"{0}\"", instanceKey), awsEx);
         }
     }
 }
        private void UploadToCdn()
        {
            try
            {
                // one thread only
                if (Interlocked.CompareExchange(ref work, 1, 0) == 0)
                {
                    var @continue = false;
                    try
                    {
                        CdnItem item;
                        if (queue.TryDequeue(out item))
                        {
                            @continue = true;

                            var cdnpath = GetCdnPath(item.Bundle.Path);
                            var key = new Uri(cdnpath).PathAndQuery.TrimStart('/');
                            var etag = AmazonS3Util.GenerateChecksumForContent(item.Response.Content, false).ToLowerInvariant();

                            var config = new AmazonS3Config
                            {
                                ServiceURL = "s3.amazonaws.com",
                                CommunicationProtocol = Protocol.HTTP
                            };
                            using (var s3 = new AmazonS3Client(s3publickey, s3privatekey, config))
                            {
                                var upload = false;
                                try
                                {
                                    var request = new GetObjectMetadataRequest
                                    {
                                        BucketName = s3bucket,
                                        Key = key,
                                    };
                                    using (var response = s3.GetObjectMetadata(request))
                                    {
                                        upload = !string.Equals(etag, response.ETag.Trim('"'), StringComparison.InvariantCultureIgnoreCase);
                                    }
                                }
                                catch (AmazonS3Exception ex)
                                {
                                    if (ex.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        upload = true;
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }

                                if (upload)
                                {
                                    var request = new PutObjectRequest
                                    {
                                        BucketName = s3bucket,
                                        CannedACL = S3CannedACL.PublicRead,
                                        Key = key,
                                        ContentType = AmazonS3Util.MimeTypeFromExtension(Path.GetExtension(key).ToLowerInvariant()),
                                    };

                                    if (ClientSettings.GZipEnabled)
                                    {
                                        var compressed = new MemoryStream();
                                        using (var compression = new GZipStream(compressed, CompressionMode.Compress, true))
                                        {
                                            new MemoryStream(Encoding.UTF8.GetBytes(item.Response.Content)).CopyTo(compression);
                                        }
                                        request.InputStream = compressed;
                                        request.AddHeader("Content-Encoding", "gzip");
                                    }
                                    else
                                    {
                                        request.ContentBody = item.Response.Content;
                                    }

                                    var cache = TimeSpan.FromDays(365);
                                    request.AddHeader("Cache-Control", string.Format("public, maxage={0}", (int)cache.TotalSeconds));
                                    request.AddHeader("Expires", DateTime.UtcNow.Add(cache).ToString("R"));
                                    request.AddHeader("Etag", etag);
                                    request.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));

                                    using (s3.PutObject(request)) { }
                                }

                                item.Bundle.CdnPath = cdnpath;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        log.Error(err);
                    }
                    finally
                    {
                        work = 0;
                        if (@continue)
                        {
                            Action upload = () => UploadToCdn();
                            upload.BeginInvoke(null, null);
                        }
                    }
                }
            }
            catch (Exception fatal)
            {
                log.Fatal(fatal);
            }
        }
Exemple #3
0
        public void UpdateIndex(string path, EntityIndex index)
        {
            var serialised = SerialiseIndex(index.Entries);
            var stream = new MemoryStream(serialised.Length);
            var writer = new StreamWriter(stream);
            writer.Write(serialised);
            writer.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            try
            {
                using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
                {
                    // Check that the index has not been updated before pushing the change - reduce the risks.
                    try
                    {
                        using (var objectMetaDataResponse = client.GetObjectMetadata(new GetObjectMetadataRequest()
                        {
                            BucketName = Context.BucketName,
                            Key = path,
                            ETagToMatch = index.ETag
                        }))
                        {

                        }
                    }
                    catch (AmazonS3Exception awsEx)
                    {
                        if (awsEx.StatusCode != System.Net.HttpStatusCode.NotFound)
                            throw;
                    }

                    using (var putResponse = client.PutObject(new PutObjectRequest()
                    {
                        BucketName = Context.BucketName,
                        Key = path,
                        GenerateMD5Digest = true,
                        InputStream = stream
                    })) { }
                }
            }
            catch (AmazonS3Exception awsEx)
            {
                throw new DeploymentException("Failed loading group index", awsEx);
            }
        }
        public void DeployPush(string appName, string s3Location, string sourcePath)
        {
            var s3 = new S3LocationParser(s3Location);

            using (var s3Client = new Amazon.S3.AmazonS3Client(Credentials, Amazon.RegionEndpoint.USEast1))
            {
                var getRequest = new Amazon.S3.Model.GetObjectMetadataRequest
                {
                    BucketName = s3.BucketName,
                    Key = s3.Key
                };

                try
                {
                    var getResponse = s3Client.GetObjectMetadata(getRequest);

                    // If we got this far, the file already exists in the S3 bucket, so get out!
                    throw new S3KeyAlreadyExistsException(s3);
                }
                catch (AmazonS3Exception ex)
                {
                    // If we got this far, then it's because the S3 file doesn't exist.
                    // Therefore, it's OK to upload with this key.
                    var zipFileName = s3.FileName;
                    var g = Guid.NewGuid().ToString();
                    var outputFile = Path.Combine(Path.GetTempPath(), g + ".tmp");
                    ZipFile.CreateFromDirectory(sourcePath, outputFile);
                    var zipFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), zipFileName);

                    if (File.Exists(zipFile))
                        File.Delete(zipFile);

                    File.Move(outputFile, zipFile);

                    var putRequest = new Amazon.S3.Model.PutObjectRequest
                    {
                        BucketName = s3.BucketName,
                        FilePath = zipFile,
                        Key = s3.Key
                    };

                    var putResponse = s3Client.PutObject(putRequest);

                    using (var cdClient = new Amazon.CodeDeploy.AmazonCodeDeployClient(Credentials, Amazon.RegionEndpoint.USEast1))
                    {
                        var revLocation = new Amazon.CodeDeploy.Model.RevisionLocation
                        {
                            RevisionType = Amazon.CodeDeploy.RevisionLocationType.S3,
                            S3Location = new Amazon.CodeDeploy.Model.S3Location
                                            {
                                                Bucket = s3.BucketName,
                                                BundleType = Amazon.CodeDeploy.BundleType.Zip,
                                                Key = s3.Key
                                            }
                        };

                        var regRequest = new Amazon.CodeDeploy.Model.RegisterApplicationRevisionRequest
                        {
                            ApplicationName = appName,
                            Revision = revLocation
                        };

                        var regResponse = cdClient.RegisterApplicationRevision(regRequest);

                        var x = 0;
                    }
                }
            }
        }
        public static String putObject(HttpPostedFileBase file, String name)
        {
            //Create a unique file name with help of the user name that is unique too
            String filename = name + file.FileName;
            String url = server + bucket + "/" + filename;

            using (IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUCentral1))
            {

                //Check if file exists
                var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, bucket, filename);
                if (s3FileInfo.Exists)
                {
                    GetObjectMetadataRequest request = new GetObjectMetadataRequest();
                    request.BucketName = bucket;
                    request.Key = filename;

                    GetObjectMetadataResponse response = client.GetObjectMetadata(request);
                    //Get tag from Amazon file
                    String S3Tag = response.ETag.Replace("/", "").Replace("\"", "");

                    using (var md5 = MD5.Create())
                    {
                        using (var stream = file.InputStream)
                        {
                            //Get tag from local file
                            stream.Position = 0;
                            String fileTag = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
                            //Compare both tags, if they match there´s no need to upload the image
                            if (fileTag == S3Tag) return url;
                            return null;
                        }
                    }

                }
                else
                {
                    int size = file.ContentLength;

                    //Upload image to amazon s3
                    PutObjectRequest request = new PutObjectRequest();
                    request.CannedACL = S3CannedACL.PublicRead;
                    request.BucketName = bucket;
                    request.ContentType = file.ContentType;
                    request.Key = filename;
                    request.InputStream = file.InputStream;
                    client.PutObject(request);

                    //Update traffic after upload
                    PictogramsDb.UpdateTraffic(name, size);

                }
            }

            return url;
        }
 public VersionCheckResult TargetAppVersionChanged(Guid targetKey, Guid appKey, Guid localVersionKey)
 {
     try
     {
         string localETag;
         using (var localKeyStream = Utils.Serialisation.Serialise(localVersionKey))
         {
             localETag = Utils.Validation.GenerateETag(localKeyStream);
         }
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObjectMetadata(new GetObjectMetadataRequest()
             {
                 BucketName = Context.BucketName,
                 Key = GetTargetAppVersionInfoPath(targetKey, appKey),
             }))
             {
                 if (res.ETag == localETag)
                     return VersionCheckResult.NotChanged;
                 else
                     return VersionCheckResult.Changed;
             }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return VersionCheckResult.NotSet;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed checking for version updates for app with key \"{0}\" and target with the key \"{1}\".", appKey, targetKey), awsEx);
         }
     }
 }
        private void UploadToCdn()
        {
            try
            {
                // one thread only
                if (Interlocked.CompareExchange(ref work, 1, 0) == 0)
                {
                    var @continue = false;
                    try
                    {
                        CdnItem item;
                        if (queue.TryDequeue(out item))
                        {
                            @continue = true;

                            var cdnpath = GetCdnPath(item.Bundle.Path);
                            var key = new Uri(cdnpath).PathAndQuery.TrimStart('/');
                            var contentMD5 = Hasher.Base64Hash(item.Response.Content, HashAlg.MD5);
                            var compressed = new MemoryStream();

                            if (ClientSettings.GZipEnabled)
                            {
                                using (var compression = new GZipStream(compressed, CompressionMode.Compress, true))
                                {
                                    new MemoryStream(Encoding.UTF8.GetBytes(item.Response.Content)).CopyTo(compression);
                                }
                                contentMD5 = Hasher.Base64Hash(compressed.GetCorrectBuffer(), HashAlg.MD5);
                            }

                            var config = new AmazonS3Config
                            {
                                RegionEndpoint = RegionEndpoint.GetBySystemName(s3region),
                                UseHttp = true
                            };
                            using (var s3 = new AmazonS3Client(s3publickey, s3privatekey, config))
                            {
                                var upload = false;
                                try
                                {
                                    var request = new GetObjectMetadataRequest
                                        {
                                        BucketName = s3bucket,
                                        Key = key
                                    };
                                    var response = s3.GetObjectMetadata(request);
                                    upload = !string.Equals(contentMD5, response.Metadata["x-amz-meta-etag"], StringComparison.InvariantCultureIgnoreCase);
                                }
                                catch (AmazonS3Exception ex)
                                {
                                    if (ex.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        upload = true;
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }

                                if (upload)
                                {
                                    var request = new PutObjectRequest
                                    {
                                        BucketName = s3bucket,
                                        CannedACL = S3CannedACL.PublicRead,
                                        Key = key,
                                        ContentType = AmazonS3Util.MimeTypeFromExtension(Path.GetExtension(key).ToLowerInvariant())
                                    };

                                    if (ClientSettings.GZipEnabled)
                                    {
                                        request.InputStream = compressed;
                                        request.Headers.ContentEncoding = "gzip";
                                    }
                                    else
                                    {
                                        request.ContentBody = item.Response.Content;
                                    }

                                    var cache = TimeSpan.FromDays(365);
                                    request.Headers.CacheControl = string.Format("public, maxage={0}", (int) cache.TotalSeconds);
                                    request.Headers.Expires = DateTime.UtcNow.Add(cache);
                                    request.Headers.ContentMD5 = contentMD5;
                                    request.Headers["x-amz-meta-etag"] = contentMD5;
                                    //request.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));

                                    s3.PutObject(request);
                                }

                                item.Bundle.CdnPath = cdnpath;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        log.Error(err);
                    }
                    finally
                    {
                        work = 0;
                        if (@continue)
                        {
                            Action upload = () => UploadToCdn();
                            upload.BeginInvoke(null, null);
                        }
                    }
                }
            }
            catch (Exception fatal)
            {
                log.Fatal(fatal);
            }
        }
        public Dictionary<string, DataTable> ScanProfile(ScanRequest Request)
        {
            Dictionary<string, DataTable> ScanResults = new Dictionary<string, DataTable>();
            DataTable UserDetailsTable = GetUsersDetailsTable();
            DataTable EC2DetailsTable = GetEC2DetailsTable();
            DataTable S3DetailsTable = GetS3DetailsTable();
            string accountid = "";
            Amazon.Runtime.AWSCredentials credential;
            var aprofile = Request.Profile;
            var regions2process = Request.Regions;
            var SubmitResults = Request.ResultQueue;
            try
            {
                credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
                //Try to get the AccountID ID//

                #region UserDetails
                var iam = new AmazonIdentityManagementServiceClient(credential);

                var myUserList = iam.ListUsers().Users;

                try
                {
                    accountid = myUserList[0].Arn.Split(':')[4];//Get the ARN and extract the AccountID ID
                    accountid = "ID: " + accountid;// Prefix added because Excel exsucks.
                }
                catch
                {
                    accountid = "?";
                }

                try // Send command to AWS to generate a Credential Report
                { var createcredreport = iam.GenerateCredentialReport(); }
                catch (Exception)
                { throw; }

                bool needreport = true;

                Amazon.IdentityManagement.Model.GetCredentialReportResponse credreport = new GetCredentialReportResponse();
                DateTime getreportstart = DateTime.Now;
                DateTime getreportfinish = DateTime.Now;
                while (needreport)
                {
                    try
                    {
                        credreport = iam.GetCredentialReport();
                        needreport = false;
                        getreportfinish = DateTime.Now;
                        var dif = getreportstart - getreportfinish;  //Just a check on how long it takes.

                        //Extract data from CSV Stream into DataTable
                        var streambert = credreport.Content;
                        streambert.Position = 0;
                        StreamReader sr = new StreamReader(streambert);
                        string myStringRow = sr.ReadLine();
                        if (myStringRow != null) myStringRow = sr.ReadLine();//Dump the header line
                        while (myStringRow != null)
                        {
                            var arow = myStringRow.Split(",".ToCharArray()[0]);

                            var newrow = new object[UserDetailsTable.Columns.Count];
                            newrow[0] = accountid;
                            newrow[1] = aprofile;
                            newrow[2] = ""; //UserID not in report. pull it later.
                            newrow[3] = arow[0];
                            newrow[4] = arow[1];
                            newrow[5] = arow[2];
                            newrow[6] = arow[3];
                            newrow[7] = arow[4];
                            newrow[8] = arow[5];
                            newrow[9] = arow[6];
                            newrow[10] = arow[7];
                            newrow[11] = arow[8];
                            newrow[12] = arow[9];
                            newrow[13] = arow[10];
                            newrow[14] = arow[11];
                            newrow[15] = arow[12];
                            newrow[16] = arow[13];
                            newrow[17] = arow[14];
                            newrow[18] = arow[15];
                            newrow[19] = arow[16];
                            newrow[20] = arow[17];
                            newrow[21] = arow[18];
                            newrow[22] = arow[19];
                            newrow[23] = arow[20];
                            newrow[24] = arow[21];
                            RawUsers.Rows.Add(newrow);
                            UserDetailsTable.Rows.Add(newrow);
                            myStringRow = sr.ReadLine();
                        }
                        sr.Close();
                        sr.Dispose();

                    }
                    catch (Exception ex)
                    {
                        string test = "";
                        //Deal with this later if necessary.
                    }
                }

                foreach (var auser in myUserList)//Fill in the userID.  Why?  because it exists.
                {
                    string auserid = auser.UserId;
                    string arn = auser.Arn;
                    string username = auser.UserName;
                    string policylist = "";
                    string aklist = "";
                    string groups = "";

                    ListAccessKeysRequest LAKREQ = new ListAccessKeysRequest();
                    LAKREQ.UserName = username;
                    ListAccessKeysResult LAKRES = iam.ListAccessKeys(LAKREQ);
                    foreach (var blivet in LAKRES.AccessKeyMetadata)
                    {
                        if (aklist.Length > 1) aklist += "\n";
                        aklist += blivet.AccessKeyId + "  :  " + blivet.Status;
                    }

                    ListAttachedUserPoliciesRequest LAUPREQ = new ListAttachedUserPoliciesRequest();
                    LAUPREQ.UserName = username;
                    ListAttachedUserPoliciesResult LAUPRES = iam.ListAttachedUserPolicies(LAUPREQ);
                    foreach (var apol in LAUPRES.AttachedPolicies)
                    {
                        if (policylist.Length > 1) policylist += "\n";
                        policylist += apol.PolicyName;
                    }

                    //Need to get policy and group info outta user
                    var groopsreq = new ListGroupsForUserRequest();
                    groopsreq.UserName = username;
                    ListGroupsForUserResult LG = iam.ListGroupsForUser(groopsreq);
                    foreach (var agroup in LG.Groups)
                    {
                        if (groups.Length > 1) groups += "\n";
                        groups += agroup.GroupName;
                    }

                    foreach (DataRow myrow in UserDetailsTable.Rows)
                    {
                        if (myrow["ARN"].Equals(arn))
                        {
                            myrow["UserID"] = auserid;
                            myrow["User-Policies"] = policylist;
                            myrow["Access-Keys"] = aklist;
                            myrow["Groups"] = groups;
                        }
                    }

                }
                #endregion

                #region S3Details
                try {

                AmazonS3Client S3Client = new AmazonS3Client(credential,Amazon.RegionEndpoint.USEast1);
                ListBucketsResponse response = S3Client.ListBuckets();
                foreach (S3Bucket abucket in response.Buckets)
                {

                    DataRow abucketrow = GetS3DetailsTable().NewRow();
                    var name = abucket.BucketName;

                    GetBucketLocationRequest gbr = new GetBucketLocationRequest();
                    gbr.BucketName=name;
                    GetBucketLocationResponse location = S3Client.GetBucketLocation(gbr);
                    var region = location.Location.Value;
                    if (region.Equals(""))region="us-east-1";
                    var pointy = RegionEndpoint.GetBySystemName(region);

                    //Build a config that references the buckets region.
                    AmazonS3Config S3C = new AmazonS3Config();
                    S3C.RegionEndpoint=pointy;
                    AmazonS3Client BS3Client = new AmazonS3Client(credential, S3C);

                    var createddate = abucket.CreationDate;
                    string owner = "";
                    string grants = "";
                    string tags = "";
                    string lastaccess = "";
                    string defaultpage = "";
                    string website = "";
                    //Now start pulling der einen data.

                    GetACLRequest GACR = new GetACLRequest();
                    GACR.BucketName = name;
                    var ACL = BS3Client.GetACL(GACR);
                    var grantlist = ACL.AccessControlList;
                    owner = grantlist.Owner.DisplayName;
                    foreach (var agrant in grantlist.Grants)
                    {
                        if (grants.Length > 1) grants += "\n";
                        var gName = agrant.Grantee.DisplayName;
                        var gType = agrant.Grantee.Type.Value;
                        var aMail = agrant.Grantee.EmailAddress;

                        if (gType.Equals("Group"))
                        {
                            grants +=  gType + " - " + agrant.Grantee.URI + " - " + agrant.Permission + " - " + aMail  ;
                        }
                        else
                        {
                            grants += gName + " - "+ agrant.Permission + " - " + aMail;
                        }
                    }

                    GetObjectMetadataRequest request = new GetObjectMetadataRequest();
                    request.BucketName = name;
                    GetObjectMetadataResponse MDresponse = BS3Client.GetObjectMetadata(request);
                    lastaccess = MDresponse.LastModified.ToString();
                    //defaultpage = MDresponse.WebsiteRedirectLocation;

                    GetBucketWebsiteRequest GBWReq = new GetBucketWebsiteRequest();
                    GBWReq.BucketName = name;
                    GetBucketWebsiteResponse GBWRes = BS3Client.GetBucketWebsite(GBWReq);

                    defaultpage = GBWRes.WebsiteConfiguration.IndexDocumentSuffix;

                    if (defaultpage != null)
                    {
                        website = @"http://" + name + @".s3-website-" + region + @".amazonaws.com/" + defaultpage;
                    }

                    //Amazon.S3.Model.req

                    abucketrow["AccountID"] = accountid;
                    abucketrow["Profile"] = aprofile;
                    abucketrow["Bucket"] = name;
                    abucketrow["Region"] = region;
                    abucketrow["CreationDate"] = createddate.ToString();
                    abucketrow["LastAccess"] = lastaccess;
                    abucketrow["Owner"] = owner;
                    abucketrow["Grants"] = grants;

                    abucketrow["WebsiteHosting"] = website;
                    abucketrow["Logging"] = "X";
                    abucketrow["Events"] = "X";
                    abucketrow["Versioning"] = "X";
                    abucketrow["LifeCycle"] = "X";
                    abucketrow["Replication"] = "X";
                    abucketrow["Tags"] = "X";
                    abucketrow["RequesterPays"] = "X";
                    S3DetailsTable.Rows.Add(abucketrow.ItemArray);
                }

                }
                catch(Exception ex)
                {

                    System.Windows.Forms.MessageBox.Show("S3 Failed!\n"+ex);
                }

                #endregion

                #region GetEC2Region

                //////////////////////////////////////////////////////////

                //Foreach aregion
                foreach (var aregion in regions2process)
                {
                    //Skip GovCloud and Beijing. They require special handling and I dont need em.
                    if (aregion == Amazon.RegionEndpoint.USGovCloudWest1) continue;
                    if (aregion == Amazon.RegionEndpoint.CNNorth1) continue;
                    var region = aregion;

                    regioncounter++;

                    //Try to get scheduled events on my Profile/aregion
                    var ec2 = AWSClientFactory.CreateAmazonEC2Client(credential, region);
                    var request = new DescribeInstanceStatusRequest();
                    request.IncludeAllInstances = true;
                    Dispatcher.Invoke(doupdatePbDelegate,
                       System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { System.Windows.Controls.ProgressBar.ValueProperty, regioncounter });
                    var instatresponse = ec2.DescribeInstanceStatus(request);

                    var indatarequest = new DescribeInstancesRequest();

                    foreach (var instat in instatresponse.InstanceStatuses)
                    {

                        indatarequest.InstanceIds.Add(instat.InstanceId);
                    }
                    DescribeInstancesResult DescResult = ec2.DescribeInstances(indatarequest);

                    int count = instatresponse.InstanceStatuses.Count();

                    foreach (var instat in instatresponse.InstanceStatuses)
                    {
                        //Collect the datases
                        string instanceid = instat.InstanceId;
                        string instancename = "";
                        ProcessingLabel.Content = "Scanning -> Profile:" + aprofile + "    Region: " + region + "   Instance: " + instanceid;
                        Dispatcher.Invoke(doupdatePbDelegate,
                            System.Windows.Threading.DispatcherPriority.Background,
                            new object[] { System.Windows.Controls.ProgressBar.ValueProperty, regioncounter });

                        var status = instat.Status.Status;
                        string AZ = instat.AvailabilityZone;
                        var istate = instat.InstanceState.Name;

                        string profile = aprofile;
                        string myregion = region.ToString();
                        int eventnumber = instat.Events.Count();

                        string eventlist = "";
                        var urtburgle = DescResult.Reservations;

                        string tags = ""; // Holds the list of tags to print out.

                        var loadtags = (from t in DescResult.Reservations
                                        where t.Instances[0].InstanceId.Equals(instanceid)
                                        select t.Instances[0].Tags).AsEnumerable();

                        Dictionary<string, string> taglist = new Dictionary<string, string>();
                        foreach (var rekey in loadtags)
                        {
                            foreach (var kvp in rekey)
                            {
                                taglist.Add(kvp.Key, kvp.Value);
                            }
                        }

                        foreach (var atag in taglist)//Set instancename, and add value to combobox.
                        {
                            if (atag.Key.Equals("Name"))
                            {
                                instancename = atag.Value;
                            }
                            if (!TagFilterCombo.Items.Contains(atag.Key))
                            {
                                TagFilterCombo.Items.Add(atag.Key);
                            }
                            if (tags.Length > 1)
                            {
                                tags += "\n" + atag.Key + ":" + atag.Value;
                            }
                            else
                            {
                                tags += atag.Key + ":" + atag.Value;
                            }
                        }

                        if (eventnumber > 0)
                        {
                            foreach (var anevent in instat.Events)
                            {
                                eventlist += anevent.Description + "\n";
                            }
                        }

                        var platform = (from t in urtburgle
                                        where t.Instances[0].InstanceId.Equals(instanceid)
                                        select t.Instances[0].Platform).FirstOrDefault();
                        if (String.IsNullOrEmpty(platform)) platform = "Linux";

                        var Priv_IP = (from t in urtburgle
                                       where t.Instances[0].InstanceId.Equals(instanceid)
                                       select t.Instances[0].PrivateIpAddress).FirstOrDefault();
                        if (String.IsNullOrEmpty(Priv_IP)) Priv_IP = "?";

                        var publicIP = (from t in urtburgle
                                        where t.Instances[0].InstanceId.Equals(instanceid)
                                        select t.Instances[0].PublicIpAddress).FirstOrDefault();
                        if (String.IsNullOrEmpty(publicIP)) publicIP = "";

                        var publicDNS = (from t in urtburgle
                                         where t.Instances[0].InstanceId.Equals(instanceid)
                                         select t.Instances[0].PublicDnsName).FirstOrDefault();
                        if (String.IsNullOrEmpty(publicDNS)) publicDNS = "";

                        //Virtualization type (HVM, Paravirtual)
                        var ivirtType = (from t in urtburgle
                                         where t.Instances[0].InstanceId.Equals(instanceid)
                                         select t.Instances[0].VirtualizationType).FirstOrDefault();
                        if (String.IsNullOrEmpty(ivirtType)) ivirtType = "?";

                        // InstanceType (m3/Large etc)
                        var instancetype = (from t in urtburgle
                                            where t.Instances[0].InstanceId.Equals(instanceid)
                                            select t.Instances[0].InstanceType).FirstOrDefault();
                        if (String.IsNullOrEmpty(instancetype)) instancetype = "?";

                        var SGs = (from t in urtburgle
                                   where t.Instances[0].InstanceId.Equals(instanceid)
                                   select t.Instances[0].SecurityGroups);

                        string sglist = "";

                        if (SGs.Count() > 0)
                        {
                            foreach (var ansg in SGs.FirstOrDefault())
                            {
                                if (sglist.Length > 2) { sglist += "\n"; }
                                sglist += ansg.GroupName;
                            }
                        }
                        else
                        {
                            sglist = "_NONE!_";
                        }
                        //Add to table
                        if (String.IsNullOrEmpty(sglist)) sglist = "NullOrEmpty";

                        if (String.IsNullOrEmpty(instancename)) instancename = "";
                        string rabbit = accountid + profile + myregion + instancename + instanceid + AZ + status + eventnumber + eventlist + tags + Priv_IP + publicIP + publicDNS + istate + ivirtType + instancetype + sglist;

                        if(instancename.Contains("p1-job"))
                        {
                            string yup = "y";
                        }

                        EC2DetailsTable.Rows.Add(accountid, profile, myregion, instancename, instanceid, AZ, platform, status, eventnumber, eventlist, tags, Priv_IP, publicIP, publicDNS, istate, ivirtType, instancetype, sglist);

                    }

                }
                #endregion
                ScanResults.Add("EC2", EC2DetailsTable);
                ScanResults.Add("Users", UserDetailsTable);
                ScanResults.Add("S3", S3DetailsTable);

                return ScanResults;
            }
            catch (Exception ex)
            {
                //If we failed to connect with creds.

                string error = new string(ex.ToString().TakeWhile(c => c != '\n').ToArray());
                System.Windows.MessageBox.Show(error, Request.Profile.ToString() + " credentials failed to work.\n");
                //Try to flag the menu item so it no longer selectable, and maybe make she red.
                System.Windows.Controls.MenuItem Proot = (System.Windows.Controls.MenuItem)this.MainMenu.Items[1];
                foreach (System.Windows.Controls.MenuItem amenuitem in Proot.Items)
                {
                    if (amenuitem.Header.ToString() == aprofile.ToString())
                    {
                        amenuitem.IsCheckable = false;
                        amenuitem.IsChecked = false;
                        amenuitem.Background = Brushes.Red;
                        amenuitem.ToolTip = Request.Profile.ToString() + " credentials failed to work.\n";
                    }
                }

                ScanResults.Add("EC2", GetEC2DetailsTable());
                ScanResults.Add("Users", GetUsersDetailsTable());
                ScanResults.Add("S3", GetS3DetailsTable());

                return ScanResults;

            }
        }
Exemple #9
0
 internal bool VersionExists(Guid key)
 {
     try
     {
         using (var client = new AmazonS3Client(Context.AwsAccessKeyId, Context.AwsSecretAccessKey))
         {
             using (var res = client.GetObjectMetadata(new GetObjectMetadataRequest()
             {
                 BucketName = Context.BucketName,
                 Key = string.Format("{0}/{1}/{2}", STR_VERSIONS_CONTAINER_PATH, key.ToString("N"), STR_INFO_FILE_NAME),
             })) { return true; }
         }
     }
     catch (AmazonS3Exception awsEx)
     {
         if (awsEx.StatusCode == System.Net.HttpStatusCode.NotFound)
         {
             return false;
         }
         else
         {
             throw new DeploymentException(string.Format("Failed checking if version with key \"{0}\" exists.", key), awsEx);
         }
     }
     catch (Exception ex)
     {
         throw new DeploymentException(string.Format("Failed checking if version with key \"{0}\" exists.", key), ex);
     }
 }
Exemple #10
-1
        public void ObjectSamples()
        {
            {
                #region ListObjects Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // List all objects
                ListObjectsRequest listRequest = new ListObjectsRequest
                {
                    BucketName = "SampleBucket",
                };

                ListObjectsResponse listResponse;
                do
                {
                    // Get a list of objects
                    listResponse = client.ListObjects(listRequest);
                    foreach (S3Object obj in listResponse.S3Objects)
                    {
                        Console.WriteLine("Object - " + obj.Key);
                        Console.WriteLine(" Size - " + obj.Size);
                        Console.WriteLine(" LastModified - " + obj.LastModified);
                        Console.WriteLine(" Storage class - " + obj.StorageClass);
                    }

                    // Set the marker property
                    listRequest.Marker = listResponse.NextMarker;
                } while (listResponse.IsTruncated);

                #endregion
            }

            {
                #region GetObject Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a GetObject request
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1"
                };

                // Issue request and remember to dispose of the response
                using (GetObjectResponse response = client.GetObject(request))
                {
                    using (StreamReader reader = new StreamReader(response.ResponseStream))
                    {
                        string contents = reader.ReadToEnd();
                        Console.WriteLine("Object - " + response.Key);
                        Console.WriteLine(" Version Id - " + response.VersionId);
                        Console.WriteLine(" Contents - " + contents);
                    }
                }

                #endregion
            }

            {
                #region GetObjectMetadata Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();


                // Create a GetObjectMetadata request
                GetObjectMetadataRequest request = new GetObjectMetadataRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1"
                };

                // Issue request and view the response
                GetObjectMetadataResponse response = client.GetObjectMetadata(request);
                Console.WriteLine("Content Length - " + response.ContentLength);
                Console.WriteLine("Content Type - " + response.Headers.ContentType);
                if (response.Expiration != null)
                {
                    Console.WriteLine("Expiration Date - " + response.Expiration.ExpiryDate);
                    Console.WriteLine("Expiration Rule Id - " + response.Expiration.RuleId);
                }

                #endregion
            }

            {
                #region PutObject Sample 1

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a PutObject request
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    ContentBody = "This is sample content..."
                };

                // Put object
                PutObjectResponse response = client.PutObject(request);

                #endregion
            }

            {
                #region PutObject Sample 2

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a PutObject request
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    FilePath = "contents.txt"
                };

                // Put object
                PutObjectResponse response = client.PutObject(request);

                #endregion
            }

            {
                #region PutObject Sample 3

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a PutObject request
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                };
                using (FileStream stream = new FileStream("contents.txt", FileMode.Open))
                {
                    request.InputStream = stream;

                    // Put object
                    PutObjectResponse response = client.PutObject(request);
                }

                #endregion
            }

            {
                #region DeleteObject Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a DeleteObject request
                DeleteObjectRequest request = new DeleteObjectRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1"
                };

                // Issue request
                client.DeleteObject(request);

                #endregion
            }

            {
                #region DeleteObjects Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a DeleteObject request
                DeleteObjectsRequest request = new DeleteObjectsRequest
                {
                    BucketName = "SampleBucket",
                    Objects = new List<KeyVersion>
                    {
                        new KeyVersion() {Key = "Item1"},
                        // Versioned item
                        new KeyVersion() { Key = "Item2", VersionId = "Rej8CiBxcZKVK81cLr39j27Y5FVXghDK", },
                        // Item in subdirectory
                        new KeyVersion() { Key = "Logs/error.txt"}
                    }
                };

                try
                {
                    // Issue request
                    DeleteObjectsResponse response = client.DeleteObjects(request);
                }
                catch (DeleteObjectsException doe)
                {
                    // Catch error and list error details
                    DeleteObjectsResponse errorResponse = doe.Response;

                    foreach (DeletedObject deletedObject in errorResponse.DeletedObjects)
                    {
                        Console.WriteLine("Deleted item " + deletedObject.Key);
                    }
                    foreach (DeleteError deleteError in errorResponse.DeleteErrors)
                    {
                        Console.WriteLine("Error deleting item " + deleteError.Key);
                        Console.WriteLine(" Code - " + deleteError.Code);
                        Console.WriteLine(" Message - " + deleteError.Message);
                    }
                }

                #endregion
            }

            {
                #region CopyObject Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                CopyObjectRequest request = new CopyObjectRequest
                {
                    SourceBucket = "SampleBucket",
                    SourceKey = "Item1",
                    DestinationBucket = "AnotherBucket",
                    DestinationKey = "Copy1",
                    CannedACL = S3CannedACL.PublicRead
                };

                // Issue request
                client.CopyObject(request);

                #endregion
            }

            {
                #region CopyObject Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Create a CopyObject request
                CopyObjectRequest request = new CopyObjectRequest
                {
                    SourceBucket = "SampleBucket",
                    SourceKey = "Item1",
                    DestinationBucket = "AnotherBucket",
                    DestinationKey = "Copy1",
                    CannedACL = S3CannedACL.PublicRead
                };

                // Issue request
                client.CopyObject(request);

                #endregion
            }

            {
                #region ListVersions Sample

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Turn versioning on for a bucket
                client.PutBucketVersioning(new PutBucketVersioningRequest
                {
                    BucketName = "SampleBucket",
                    VersioningConfig = new S3BucketVersioningConfig { Status = "Enable" }
                });

                // Populate bucket with multiple items, each with multiple versions
                PopulateBucket(client, "SampleBucket");

                // Get versions
                ListVersionsRequest request = new ListVersionsRequest
                {
                    BucketName = "SampleBucket"
                };

                // Make paged ListVersions calls
                ListVersionsResponse response;
                do
                {
                    response = client.ListVersions(request);
                    // View information about versions
                    foreach (var version in response.Versions)
                    {
                        Console.WriteLine("Key = {0}, Version = {1}, IsLatest = {2}, LastModified = {3}, Size = {4}",
                            version.Key,
                            version.VersionId,
                            version.IsLatest,
                            version.LastModified,
                            version.Size);
                    }

                    request.KeyMarker = response.NextKeyMarker;
                    request.VersionIdMarker = response.NextVersionIdMarker;
                } while (response.IsTruncated);

                #endregion
            }

            {
                #region Multipart Upload Sample

                int MB = (int)Math.Pow(2, 20);

                // Create a client
                AmazonS3Client client = new AmazonS3Client();

                // Define input stream
                Stream inputStream = Create13MBDataStream();

                // Initiate multipart upload
                InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1"
                };
                InitiateMultipartUploadResponse initResponse = client.InitiateMultipartUpload(initRequest);

                // Upload part 1
                UploadPartRequest uploadRequest = new UploadPartRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    UploadId = initResponse.UploadId,
                    PartNumber = 1,
                    PartSize = 5 * MB,
                    InputStream = inputStream
                };
                UploadPartResponse up1Response = client.UploadPart(uploadRequest);

                // Upload part 2
                uploadRequest = new UploadPartRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    UploadId = initResponse.UploadId,
                    PartNumber = 2,
                    PartSize = 5 * MB,
                    InputStream = inputStream
                };
                UploadPartResponse up2Response = client.UploadPart(uploadRequest);

                // Upload part 3
                uploadRequest = new UploadPartRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    UploadId = initResponse.UploadId,
                    PartNumber = 3,
                    InputStream = inputStream
                };
                UploadPartResponse up3Response = client.UploadPart(uploadRequest);

                // List parts for current upload
                ListPartsRequest listPartRequest = new ListPartsRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    UploadId = initResponse.UploadId
                };
                ListPartsResponse listPartResponse = client.ListParts(listPartRequest);
                Debug.Assert(listPartResponse.Parts.Count == 3);

                // Complete the multipart upload
                CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest
                {
                    BucketName = "SampleBucket",
                    Key = "Item1",
                    UploadId = initResponse.UploadId,
                    PartETags = new List<PartETag>
                    {
                        new PartETag { ETag = up1Response.ETag, PartNumber = 1 },
                        new PartETag { ETag = up2Response.ETag, PartNumber = 2 },
                        new PartETag { ETag = up3Response.ETag, PartNumber = 3 }
                    }
                };
                CompleteMultipartUploadResponse compResponse = client.CompleteMultipartUpload(compRequest);

                #endregion
            }
        }