Ejemplo n.º 1
0
        public MainPage()
        {
            InitializeComponent();
            this.DataContext = this;

            SimpleDB.Client = AWSClientFactory.CreateAmazonSimpleDBClient();

            PropertyChanged += ((object sender, PropertyChangedEventArgs e) =>
            {
                if (string.Compare(e.PropertyName, "SelectedIndex", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (SelectedIndex >= 0)
                    {
                        //Update the bucket-name with the currently selected one.
                        this.DomainName = this.DomainNameList[SelectedIndex];
                    }
                }
                else if (string.Compare(e.PropertyName, "DomainName", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (string.IsNullOrEmpty(_domainName))
                    {
                        this.IsDomainNameSet = false;
                    }
                    else
                    {
                        this.IsDomainNameSet = true;
                    }
                }
            });
        }
Ejemplo n.º 2
0
        public RegionDetails GetRegionData(AwsRegionLocations region)
        {
            var regionEndpoint = region.ToAwsRegionEndpoint();

            // Get an Ec2Client for the current region
            var client = ec2Clients.GetOrAdd(region, r => AWSClientFactory.CreateAmazonEC2Client(credentials, regionEndpoint));

            // Get instances within the region
            // Start by creating the request
            var request = new DescribeInstancesRequest();

            // Add a filter to the request so that it only returns instances that are either in "Running" or "Pending" state.
            request.Filters.Add(new Filter("instance-state-code", new List <string>()
            {
                ((ushort)InstanceStatuses.Running).ToString(),
                ((ushort)InstanceStatuses.Pending).ToString()
            }));

            // Send the request to Amazon
            var reservations = client.DescribeInstances(request).Reservations;

            return(new RegionDetails()
            {
                Name = regionEndpoint.SystemName,
                Region = region,
                Instances = reservations.SelectMany(x => x.Instances).Select(x => x.ToInstanceInfo()).ToList()
            });
        }
Ejemplo n.º 3
0
        public static void InvokeListBuckets()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            IAmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USWest2);

            try
            {
                ListBucketsResponse response = s3Client.ListBuckets();
                int numBuckets = 0;
                numBuckets = response.Buckets.Count;

                Console.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s).");
            }
            catch (AmazonS3Exception ex)
            {
                if (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                    ex.ErrorCode.Equals("InvalidSecurity"))
                {
                    Console.WriteLine("Please check the provided AWS access credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3 yet, you can sign up at http://aws.amazon.com/s3.");
                }
                else
                {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }
            Console.WriteLine();
        }
Ejemplo n.º 4
0
        public ListVersionsResponse MssListFileVersions(string sObjectKey)
        {
            AmazonS3 client      = AWSClientFactory.CreateAmazonS3Client(S3ACCESSKEY, S3SECRETKEY);
            string   BUCKET_NAME = ConfigurationManager.AppSettings["AWSBUCKET"];

            return(client.ListVersions(new ListVersionsRequest().WithBucketName(BUCKET_NAME).WithKeyMarker(sObjectKey)));
        }
Ejemplo n.º 5
0
        private string FindNewestInstanceId(AwsRegionLocations region)
        {
            var client = ec2Clients.GetOrAdd(region, r => AWSClientFactory.CreateAmazonEC2Client(credentials, region.ToAwsRegionEndpoint()));

            // Get instances within the region
            // Start by creating the request
            var request = new DescribeInstancesRequest();

            // Add a filter to the request so that it only returns instances that are either in "Running" state.
            request.Filters.Add(new Filter("instance-state-code", new List <string>()
            {
                ((ushort)InstanceStatuses.Running).ToString(),
            }));

            // Send the request to Amazon
            var reservations = client.DescribeInstances(request).Reservations;

            var instances = reservations.SelectMany(x => x.Instances);

            if (instances.Any())
            {
                var newestInstance = instances.OrderByDescending(i => i.LaunchTime).First();
                return(newestInstance.InstanceId);
            }
            return(null);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Register for publishing messages to SNS
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IHaveFulfilledPublishRequirements WithSnsMessagePublisher <T>() where T : Message
        {
            Log.Info("Adding SNS publisher");
            _subscriptionConfig.Topic = typeof(T).ToTopicName();
            var publishEndpointProvider = CreatePublisherEndpointProvider(_subscriptionConfig);

            Bus.SerialisationRegister.AddSerialiser <T>(_serialisationFactory.GetSerialiser <T>());

            foreach (var region in Bus.Config.Regions)
            {
                var eventPublisher = new SnsTopicByName(
                    publishEndpointProvider.GetLocationName(),
                    AWSClientFactory.CreateAmazonSimpleNotificationServiceClient(RegionEndpoint.GetBySystemName(region)),
                    Bus.SerialisationRegister);

                if (!eventPublisher.Exists())
                {
                    eventPublisher.Create();
                }

                Bus.AddMessagePublisher <T>(eventPublisher, region);
            }

            Log.Info(string.Format("Created SNS topic publisher - Topic: {0}", _subscriptionConfig.Topic));

            return(this);
        }
Ejemplo n.º 7
0
        public static void InvokeListQueues()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            // Print the number of Amazon SimpleDB domains.
            IAmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint.USWest2);

            try
            {
                ListQueuesResponse sqsResponse = sqs.ListQueues(new ListQueuesRequest());

                int numQueues = 0;
                numQueues = sqsResponse.QueueUrls.Count;
                Console.WriteLine("You have " + numQueues + " Amazon SQS queues(s).");
            }
            catch (AmazonSQSException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
            }
            Console.WriteLine();
        }
Ejemplo n.º 8
0
        public void SetUp()
        {
            _client = AWSClientFactory.CreateAmazonSQSClient(Access_Key_ID, Secret_Access_Key);

            //Ensure we create a test queue for the test cases. And remember to delete it in the teardown method.
            bool hasCallbackArrived = false;
            SQSResponseEventHandler <object, ResponseEventArgs> handler = null;

            handler = delegate(object sender, ResponseEventArgs args)
            {
                ISQSResponse result = args.Response;
                //Unhook from event.
                _client.OnSQSResponse -= handler;
                hasCallbackArrived     = true;
            };

            //Hook to event
            _client.OnSQSResponse += handler;
            _client.CreateQueue(new CreateQueueRequest {
                QueueName = _queue_UnitTesting, DefaultVisibilityTimeout = 3
            });

            EnqueueConditional(() => hasCallbackArrived);
            EnqueueTestComplete();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This static method deletes a SQS queue. Once deleted, the queue and any messages on it will no longer be available.
        /// </summary>
        /// <param name="QueueName">The name of the queue to be deleted</param>
        /// <param name="RegionEndpoint">Endpoint corresponding to the AWS region where the queue is located</param>
        /// <param name="ErrorMessage">String that will receive the error message, if an error occurs</param>
        /// <returns></returns>
        public static bool DestroySQSQueue(string QueueName, RegionEndpoint RegionEndpoint, out string ErrorMessage, string AWSAccessKey = "", string AWSSecretKey = "")
        {
            bool result = false;

            ErrorMessage = "";
            IAmazonSQS queueClient;


            if (!String.IsNullOrWhiteSpace(QueueName))
            {
                if (!String.IsNullOrEmpty(AWSAccessKey))
                {
                    queueClient = AWSClientFactory.CreateAmazonSQSClient(AWSAccessKey, AWSSecretKey, RegionEndpoint);
                }
                else
                {
                    queueClient = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint);
                }
                try
                {
                    // Load the queue URL
                    string url = queueClient.GetQueueUrl(QueueName).QueueUrl;

                    // Destroy the queue
                    queueClient.DeleteQueue(url);
                }
                catch (Exception ex)
                {
                    ErrorMessage = ex.Message;
                }
            }

            return(result);
        }
Ejemplo n.º 10
0
        public static bool CheckConnection()
        {
            try
            {
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                    App.Settings.AWSAccessKey,
                    App.Settings.AWSSecretKey,
                    new AmazonEC2Config {
                    ServiceURL = App.Settings.ServiceUrl
                }
                    );

                ec2.DescribeInstances(new DescribeInstancesRequest());

                return(true);
            }
            catch (AmazonEC2Exception ex)
            {
                string message = ex.Message + "\r\n" +
                                 "Response Status Code: " + ex.StatusCode + "\r\n" +
                                 "Error Code: " + ex.ErrorCode + "\r\n" +
                                 "Error Type: " + ex.ErrorType + "\r\n" +
                                 "Request ID: " + ex.RequestId;
                ExceptionDialog.Show(new AmazonEC2Exception(message, ex));
                return(false);
            }
            catch (Exception ex)
            {
                ExceptionDialog.Show(ex);
                return(false);
            }
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            try
            {
                _s3Client = AWSClientFactory.CreateAmazonS3Client();

                string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), BACKUP_JOB_FILE);

                XmlSerializer serializer = new XmlSerializer(typeof(List <BackupJob>));

                List <BackupJob> jobs = (List <BackupJob>)serializer.Deserialize(new FileStream(path, FileMode.Open));

                foreach (var job in jobs.Where(p => p.Active))
                {
                    ExecuteBackupJob(job);

                    _logger.Info("finished uploading: " + job.LocalRoot);
                }

                serializer.Serialize(new FileStream(path, FileMode.Create), jobs);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message + " " + ex.StackTrace);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Register for publishing messages to SQS
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IHaveFulfilledPublishRequirements WithSqsMessagePublisher<T>(Action<SqsWriteConfiguration> configBuilder) where T : Message
        {
            Log.Info("Adding SQS publisher");

            var config = new SqsWriteConfiguration();
            configBuilder(config);

            var messageTypeName = typeof(T).Name.ToLower();
            var queueName = string.IsNullOrWhiteSpace(config.QueueName)
                ? messageTypeName
                : messageTypeName + "-" + config.QueueName;
            _publishConfig.QueueName = queueName;

            var publishEndpointProvider = CreatePublisherEndpointProvider(_publishConfig);
            var locationName = publishEndpointProvider.GetLocationName();

            var eventPublisher = new SqsPublisher(
                locationName,
                AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint.GetBySystemName(Bus.Config.Region)),
                config.RetryCountBeforeSendingToErrorQueue,
                Bus.SerialisationRegister);

            if (!eventPublisher.Exists())
                eventPublisher.Create(config);

            Bus.SerialisationRegister.AddSerialiser<T>(_serialisationFactory.GetSerialiser<T>());

            Bus.AddMessagePublisher<T>(eventPublisher);

            Log.Info(string.Format("Created SQS publisher - MessageName: {0}, QueueName: {1}", messageTypeName, locationName));

            return this;
        }
        static void Main(string[] args)
        {
            foreach (var enumerableAllRegion in  RegionEndpoint.EnumerableAllRegions)
            {
                System.Console.Out.WriteLine(enumerableAllRegion.DisplayName + " " + enumerableAllRegion.SystemName);
            }

            System.Net.WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();

            AmazonS3Config config = new AmazonS3Config();

            //config.ProxyHost = "localhost";
            //config.ProxyPort = 3128;
            //config.ProxyCredentials = new
            config.RegionEndpoint = RegionEndpoint.EUWest1;
            //config.UseHttp = true;

            var client = AWSClientFactory.CreateAmazonS3Client("", "", config);

            //client.
            var response = client.ListBuckets();

            foreach (var bucket in response.Buckets)
            {
                System.Console.Out.WriteLine(bucket.BucketName);
            }

            System.Console.Out.WriteLine("--end--");
            System.Console.ReadLine();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// A Wrapper for the AWS.net SDK
        /// </summary>
        public S3Storage()
        {
            var accessKeyId     = _dbContext.Key.SingleOrDefault(k => k.Name == "AccessKeyId").Data;
            var secretAccessKey = _dbContext.Key.SingleOrDefault(k => k.Name == "SecretAccessKey").Data;

            _client = AWSClientFactory.CreateAmazonS3Client(accessKeyId, secretAccessKey, RegionEndpoint.USEast1);
        }
Ejemplo n.º 15
0
        public S3FileStorage()
        {
            var config = ConfigurationManager.AppSettings;

            _bucketName = config["BucketName"];
            _s3Client   = AWSClientFactory.CreateAmazonS3Client(config["AWSAccessKey"], config["AWSSecretKey"], Amazon.RegionEndpoint.EUCentral1);
        }
        public void SetUp()
        {
            AWSCredentials credentials = AmbientCredentials.GetCredentials();

            Ec2Client = AWSClientFactory.CreateAmazonEC2Client(credentials);
            Service   = new SecurityGroupService(Ec2Client);
        }
Ejemplo n.º 17
0
        public static string CreateFileShare(string fileName, string fileContent)
        {
            try
            {
                var s3Client = AWSClientFactory.CreateAmazonS3Client();

                String S3_KEY  = string.Format("{0}{1}_{2}.pdf", AMAZONPublicFolder, fileName, Guid.NewGuid().ToString());
                var    request = new PutObjectRequest()
                {
                    BucketName  = AMAZONBucket,
                    Key         = S3_KEY,
                    ContentBody = fileContent
                };

                s3Client.PutObject(request);

                string preSignedURL = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
                {
                    BucketName = AMAZONBucket,
                    Key        = S3_KEY,
                    Expires    = System.DateTime.Now.AddMinutes(60 * 72)
                });

                return(preSignedURL);
            }
            catch (Amazon.S3.AmazonS3Exception ex)
            {
                throw;
            }
            catch (Exception e)
            {
                throw;
            }
        }
Ejemplo n.º 18
0
        public override bool Execute()
        {
            using (var ec2Client = AWSClientFactory.CreateAmazonEC2Client(
                       AwsAccessKey, AwsSecretKey, new AmazonEC2Config().WithServiceURL("https://eu-west-1.ec2.amazonaws.com")))
            {
                var runInstanceResponse = ec2Client.RunInstances(
                    new RunInstancesRequest()
                    .WithImageId(AmiId)
                    .WithMinCount(1)
                    .WithMaxCount(1)
                    .WithInstanceType(InstanceType)
                    .WithSecurityGroup(SecurityGroup)
                    .WithKeyName(KeyPair));
                var instanceId = runInstanceResponse.RunInstancesResult.Reservation.RunningInstance[0].InstanceId;
                while (IsInstancePending(ec2Client, instanceId))
                {
                    Log.LogMessage("Instance starting up...");
                    Thread.Sleep(5000);
                }

                var instancePublicAddress = GetPublicDnsName(ec2Client, instanceId);
                Log.LogMessage("{0} instance started!", instancePublicAddress);
                InstancePublicDnsName = instancePublicAddress;
                InstanceId            = instanceId;
                return(true);
            }
        }
Ejemplo n.º 19
0
        private static List <string> GetAllQueues(RegionEndpoint regionEndpoint, string queueName)
        {
            var client = AWSClientFactory.CreateAmazonSQSClient(regionEndpoint);
            var topics = client.ListQueues(new ListQueuesRequest());

            return(topics.QueueUrls.Where(x => x.IndexOf(queueName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList());
        }
        public static void InvokeDescribeJobFlows()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            // Print the number of Amazon SimpleDB domains.
            IAmazonElasticMapReduce emr = AWSClientFactory.CreateAmazonElasticMapReduceClient(RegionEndpoint.USWest2);

            try
            {
                DescribeJobFlowsResponse emrResponse = emr.DescribeJobFlows(new DescribeJobFlowsRequest());

                int numFlows = 0;
                numFlows = emrResponse.JobFlows.Count;
                Console.WriteLine("You have " + numFlows + " Amazon Elastic MapReduce job flow(s).");
            }
            catch (AmazonElasticMapReduceException ex)
            {
                if (ex.ErrorCode.Equals("OptInRequired"))
                {
                    Console.WriteLine("You are not signed for Amazon Elastic MapReduce.");
                    Console.WriteLine("You can sign up at http://aws.amazon.com/elasticmapreduce.");
                }
                else
                {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Error Type: " + ex.ErrorType);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }
            Console.WriteLine();
        }
Ejemplo n.º 21
0
        public bool IndexExists(string indexName)
        {
            var amazonSearchParameters = this.GetAmazonParams();
            var region = RegionEndpoint.GetBySystemName(amazonSearchParameters[Region]);

            using (IAmazonCloudSearch cloudSearchClient = AWSClientFactory.CreateAmazonCloudSearchClient(amazonSearchParameters[AccessKey], amazonSearchParameters[SecretAccessKey], region))
            {
                bool exists = false;
                try
                {
                    ListDomainNamesResponse response = cloudSearchClient.ListDomainNames();
                    exists = response.DomainNames.ContainsKey(indexName);
                }
                catch (BaseException ex)
                {
                    Log.Write(ex.InnerException.Message);
                }
                catch (ArgumentNullException ex)
                {
                    Log.Write(ex.InnerException.Message);
                }

                return(exists);
            }
        }
Ejemplo n.º 22
0
        public ErrorTypes AddTask(TaskQueueData oTask, Priority oPriority)
        {
            ErrorTypes eResult     = ErrorTypes.Unknown;
            string     strUrlQueue = GetQueueUrl(oPriority);

            try
            {
                oTask.VisibilityTimeout = m_oVisibilityTimeout;

                string strData = TaskQueueData.SerializeToXml(oTask);

                using (AmazonSQS oSQSClient = AWSClientFactory.CreateAmazonSQSClient())
                {
                    SendMessageRequest oSendMessageRequest = new SendMessageRequest();
                    oSendMessageRequest.QueueUrl    = strUrlQueue;
                    oSendMessageRequest.MessageBody = strData;
                    oSQSClient.SendMessage(oSendMessageRequest);
                    eResult = ErrorTypes.NoError;
                }
            }
            catch (AmazonSQSException)
            {
                eResult = ErrorTypes.TaskQueue;
            }
            catch
            {
                eResult = ErrorTypes.TaskQueue;
            }

            return(eResult);
        }
Ejemplo n.º 23
0
        public byte[] FetchFile(string sObjectKey, string sVersionId)
        {
            AmazonS3 client      = AWSClientFactory.CreateAmazonS3Client(S3ACCESSKEY, S3SECRETKEY);
            string   BUCKET_NAME = ConfigurationManager.AppSettings["AWSBUCKET"];

            GetObjectRequest request = new GetObjectRequest();

            request.WithKey(sObjectKey);
            request.WithBucketName(BUCKET_NAME);

            if (sVersionId != "")
            {
                request.WithVersionId(sVersionId);
            }

            GetObjectResponse response = client.GetObject(request);

            byte[] buffer = new byte[response.ContentLength];

            int          read;
            MemoryStream ms = new MemoryStream();

            while ((read = response.ResponseStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }

            return(ms.ToArray());
        }
Ejemplo n.º 24
0
        public ErrorTypes RemoveTask(object key)
        {
            ErrorTypes eResult = ErrorTypes.Unknown;

            try
            {
                SQSDataKey oSQSDataKey = (SQSDataKey)key;
                string     strUrlQueue = GetQueueUrl(oSQSDataKey.m_oPriority);

                using (AmazonSQS oSQSClient = AWSClientFactory.CreateAmazonSQSClient())
                {
                    DeleteMessageRequest oDeleteRequest = new DeleteMessageRequest();
                    oDeleteRequest.QueueUrl      = strUrlQueue;
                    oDeleteRequest.ReceiptHandle = (string)oSQSDataKey.m_strReceiptHandle;

                    oSQSClient.DeleteMessage(oDeleteRequest);
                    eResult = ErrorTypes.NoError;
                }
            }
            catch (AmazonSQSException)
            {
            }
            catch
            {
            }

            return(eResult);
        }
Ejemplo n.º 25
0
        private void CreateAndLaunchInstance(AwsRegionLocations region)
        {
            // Get an Ec2Client for the current region
            var client = ec2Clients.GetOrAdd(region, r => AWSClientFactory.CreateAmazonEC2Client(credentials, region.ToAwsRegionEndpoint()));

            var securityGroupId      = EnsureSecurityGroupExists(region);
            var availableSubnets     = client.DescribeSubnets().Subnets.OrderByDescending(x => x.AvailableIpAddressCount);
            var networkSpecification = new InstanceNetworkInterfaceSpecification()
            {
                DeviceIndex = 0,
                SubnetId    = availableSubnets.First().SubnetId,
                Groups      = new List <string>()
                {
                    securityGroupId
                },
                AssociatePublicIpAddress = true
            };
            var networkSpecifications = new List <InstanceNetworkInterfaceSpecification>()
            {
                networkSpecification
            };

            var launchRequest = new RunInstancesRequest()
            {
                ImageId           = GetAmiId(client, amiName),
                InstanceType      = "t2.micro",
                MinCount          = 1,
                MaxCount          = 1,
                KeyName           = keyPairName,
                NetworkInterfaces = networkSpecifications
            };

            client.RunInstances(launchRequest);
        }
Ejemplo n.º 26
0
        private GetQueueAttributesResult GetTaskQueueAttr(Priority oPriority)
        {
            string strUrlQueue = GetQueueUrl(oPriority);

            GetQueueAttributesResult oGetQueueAttributesResult = null;

            try
            {
                using (AmazonSQS oSQSClient = AWSClientFactory.CreateAmazonSQSClient())
                {
                    GetQueueAttributesRequest oGetQueueAttributesRequest = new GetQueueAttributesRequest();
                    oGetQueueAttributesRequest.QueueUrl = strUrlQueue;

                    GetQueueAttributesResponse oGetQueueAttributesResponse = oSQSClient.GetQueueAttributes(oGetQueueAttributesRequest);
                    if (oGetQueueAttributesResponse.IsSetGetQueueAttributesResult())
                    {
                        oGetQueueAttributesResult = oGetQueueAttributesResponse.GetQueueAttributesResult;
                    }
                }
            }
            catch (AmazonSQSException)
            {
            }
            catch
            {
            }

            return(oGetQueueAttributesResult);
        }
Ejemplo n.º 27
0
        public string EnsureSecurityGroupExists(AwsRegionLocations region)
        {
            var regionEndpoint = region.ToAwsRegionEndpoint();

            // Get an Ec2Client for the current region
            var client = ec2Clients.GetOrAdd(region, r => AWSClientFactory.CreateAmazonEC2Client(credentials, regionEndpoint));

            // Find the VPC ID for this region
            var vpcId = client.DescribeVpcs().Vpcs.Single().VpcId;

            // Does the security group with our preset name exist?
            var matchingGroups = client.DescribeSecurityGroups().SecurityGroups.Where(x => x.GroupName == securityGroupName).ToList();

            if (matchingGroups.Any())
            {
                // If it exists, assert that it has the same VPC ID as the one we found earlier
                if (matchingGroups.Single().VpcId != vpcId)
                {
                    throw new Exception("Security Group already exists with invalid VPC.");
                }
                return(matchingGroups.Single().GroupId);
            }
            else
            {
                // It does not exist, so create it.
                return(CreateSecurityGroup(client, vpcId, securityGroupName));
            }
        }
Ejemplo n.º 28
0
    public static string PreSignedUrl(TemporaryAWSCredentials creds, string fileKey)
    {
        string url = "";

        //var s3Client = new AmazonS3Client(new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.Token)))

        ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides();

        headerOverrides.ContentType = "application/pdf";

        int secs = 0;

        do
        {
            using (var s3Client = AWSClientFactory.CreateAmazonS3Client(GetAccesskey(), GetSecretkey()))
            {
                GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
                                                 .WithBucketName(GetBucketname())
                                                 .WithKey(fileKey.TrimStart('/'))
                                                 .WithProtocol(Protocol.HTTP)
                                                 .WithVerb(HttpVerb.GET)
                                                 //.WithResponseHeaderOverrides(headerOverrides)
                                                 .WithExpires(DateTime.Now.AddMinutes(120).AddSeconds(secs));

                url = s3Client.GetPreSignedURL(request);
                secs++;
            }
        } while ((url.Contains("%2B") || url.Contains("%2b") || url.Contains("+")) && secs < 30); // try again until a signature with no + sign is generated.


        return(url);
    }
Ejemplo n.º 29
0
    private static Boolean MoveFile(string saveAsFileName, string wkBaseFolder, Int32 wkVersionNo, string currentFilePath)
    {
        try
        {
            string destFile = wkBaseFolder + "/" + wkVersionNo.ToString() + "/" + saveAsFileName;

            AmazonS3Config config = new AmazonS3Config();
            config.ServiceURL = AWSHelpers.GetS3EndPoint();
            using (var client = AWSClientFactory.CreateAmazonS3Client(AWSHelpers.GetAccesskey(), AWSHelpers.GetSecretkey(), config))
            {
                TransferUtility s3TransferUtil = new TransferUtility(client);

                TransferUtilityUploadRequest s3TrfrReq = new TransferUtilityUploadRequest();
                s3TrfrReq.CannedACL  = Amazon.S3.Model.S3CannedACL.BucketOwnerFullControl;
                s3TrfrReq.FilePath   = currentFilePath;
                s3TrfrReq.BucketName = AWSHelpers.GetBucketname();
                s3TrfrReq.Key        = destFile;
                s3TransferUtil.Upload(s3TrfrReq);

                // Delete the temporary PDF on the web server
                FileInfo TheFile = new FileInfo(s3TrfrReq.FilePath);
                if (TheFile.Exists)
                {
                    // File found so delete it.
                    TheFile.Delete();
                }
            }

            return(true);
        }
        catch (Exception ex)
        {
            return(false);
        }
    }
Ejemplo n.º 30
0
        public SqsQueueByName VerifyOrCreateQueue(string region, IMessageSerialisationRegister serialisationRegister, SqsConfiguration queueConfig)
        {
            var sqsclient = AWSClientFactory.CreateAmazonSQSClient(RegionEndpoint.GetBySystemName(region));
            var snsclient = AWSClientFactory.CreateAmazonSimpleNotificationServiceClient(RegionEndpoint.GetBySystemName(region));

            var queue = new SqsQueueByName(queueConfig.QueueName, sqsclient, queueConfig.RetryCountBeforeSendingToErrorQueue);

            var eventTopic = new SnsTopicByName(queueConfig.PublishEndpoint, snsclient, serialisationRegister);

            queue.EnsureQueueAndErrorQueueExistAndAllAttributesAreUpdated(queueConfig);

            if (!eventTopic.Exists())
            {
                eventTopic.Create();
            }

            if (!eventTopic.IsSubscribed(queue))
            {
                eventTopic.Subscribe(queue);
            }

            if (!queue.HasPermission(eventTopic))
            {
                queue.AddPermission(eventTopic);
            }

            return(queue);
        }