Example #1
0
        /// <summary>
        /// Cloud account provider.
        /// </summary>
        /// <param name="awsAccessKeyId">AWS Access Key ID.</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key.</param>
        /// <param name="serviceUrl">AWS service URL.</param>
        public CloudAccount(string awsAccessKeyId, string awsSecretAccessKey, string serviceUrl)
        {
            AmazonSimpleDBConfig clientConfig = new AmazonSimpleDBConfig();

            clientConfig.ServiceURL = serviceUrl;
            _client = new AmazonSimpleDBClient(awsAccessKeyId, awsSecretAccessKey, clientConfig);
        }
Example #2
0
        public Routes GetAllRoutes()
        {
            Routes routes = new Routes();

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                SelectRequest request =
                    new SelectRequest().WithSelectExpression(
                        string.Format("SELECT * FROM Routes "));
                SelectResponse response = client.Select(request);
                foreach (Item item in response.SelectResult.Item)
                {
                    string value = item.Attribute.GetValueByName("Id");
                    Route  route = new Route
                    {
                        Id             = Guid.Parse(item.Attribute.GetValueByName("Id")),
                        Distance       = item.Attribute.GetDoubleValueByName("Distance"),
                        LastTimeRidden = item.Attribute.GetDateTimeValueByName("LastTimeRidden"),
                        Name           = item.Attribute.GetValueByName("Name"),
                        Location       = item.Attribute.GetValueByName("Location"),
                    };
                    routes.Add(route);
                }
            }
            return(routes);
        }
Example #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this._domainName = String.Format(Settings.Default.SimpleDbDomainNameFormat, this.Context.User.Identity.Name);

            if (!this.Page.IsPostBack)
            {
                using (AmazonSimpleDBClient sdbClient = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USWest2))
                {
                    DomainHelper.CheckForDomain(this._domainName, sdbClient);
                    SelectRequest selectRequest = new SelectRequest()
                    {
                        SelectExpression = String.Format("select * from `{0}`", this._domainName)
                    };
                    SelectResponse selectResponse = sdbClient.Select(selectRequest);
                    List <Item>    items          = selectResponse.Items;
                    List <Pet>     pets           = items.Select(l => new Pet
                    {
                        Id            = l.Name,
                        PhotoThumbUrl = l.Attributes.First(a => a.Name == "PhotoThumbUrl").Value,
                        Name          = l.Attributes.First(a => a.Name == "Name").Value,
                        Birthdate     = l.Attributes.First(a => a.Name == "Birthdate").Value,
                        Sex           = l.Attributes.First(a => a.Name == "Sex").Value,
                        Type          = l.Attributes.First(a => a.Name == "Type").Value,
                        Breed         = l.Attributes.First(a => a.Name == "Breed").Value
                    }).ToList();
                    this.PetRepeater.DataSource = pets;
                    this.PetRepeater.DataBind();
                }
            }
        }
Example #4
0
        public Profiles GetProfileList()
        {
            Profiles profiles = new Profiles();

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                SelectRequest request = new SelectRequest {
                    SelectExpression = "SELECT * FROM Profiles"
                };

                SelectResponse response = client.Select(request);

                var list = from item in response.SelectResult.Item
                           select new Profile()
                {
                    Id          = Guid.Parse(item.Attribute.GetValueByName("Id")),
                    Description = item.Attribute.GetValueByName("Description"),
                    Location    = item.Attribute.GetValueByName("Location"),
                    Name        = item.Attribute.GetValueByName("Name")
                };
                foreach (Profile profile in list)
                {
                    profiles.Add(profile);
                }
            }

            return(profiles);
        }
Example #5
0
 public Default()
 {
     if (_simpleDBClient == null)
     {
         _simpleDBClient = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USWest2);
     }
     System.Threading.Thread.MemoryBarrier();
 }
        public SimpleDBAssetPersistor(string dbConnStr)
        {
            string awsKeyID     = Regex.Match(dbConnStr, "AWSKeyID=(?<keyid>.+?)(;|$)").Result("${keyid}");
            string awsSecretKey = Regex.Match(dbConnStr, "AWSSecretKey=(?<secretkey>.+?)(;|$)").Result("${secretkey}");

            m_simpleDBClient = new AmazonSimpleDBClient(awsKeyID, awsSecretKey);
            m_objectMapper   = new ObjectMapper <T>();
        }
Example #7
0
 public void TearDown()
 {
     using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
     {
         DeleteAttributesRequest request = new DeleteAttributesRequest();
         request.DomainName = RouteRepository.DomainName;
         request.ItemName   = testRoute.Id.ToString();
         client.DeleteAttributes(request);
     }
 }
Example #8
0
        public SimpleDBStorage()
        {
            var credentials = new CognitoAWSCredentials(
                Constants.CognitoIdentityPoolId,
                RegionEndpoint.EUWest1);
            var config = new AmazonSimpleDBConfig();

            config.RegionEndpoint = RegionEndpoint.EUWest1;
            client = new AmazonSimpleDBClient(credentials, config);

            Items = new List <TodoItem>();
            SetupDomain();
        }
Example #9
0
        static void ReadFromSimpleDb(AWSCredentials credentials)
        {
            var client = new AmazonSimpleDBClient(credentials, RegionEndpoint.USEast1);

            // attribute names are case sensitive
            // comparisons are lexicographical. no numeric comparisons exist
            var request  = new SelectRequest("select * from `aws-talk` WHERE `Price` > '01'");
            var response = client.Select(request);

            foreach (var item in response.Items)
            {
                Console.WriteLine("Item {0} has attributes: {1}",
                                  item.Name, String.Join(" ; ", item.Attributes.Select(a => string.Format("{0}={1}", a.Name, a.Value))));
            }
        }
Example #10
0
        static void WriteToSimpleDb(AWSCredentials credentials)
        {
            var client = new AmazonSimpleDBClient(credentials, RegionEndpoint.USEast1);

            var request  = new CreateDomainRequest("aws-talk");
            var response = client.CreateDomain(request);

            var putData = new PutAttributesRequest("aws-talk", "products/" + Guid.NewGuid().ToString(),
                                                   new List <ReplaceableAttribute>()
            {
                new ReplaceableAttribute("Name", "Couch", true),
                new ReplaceableAttribute("Price", "20", true)
            });

            client.PutAttributes(putData);
        }
Example #11
0
        public static string GetSimpleDBDomainsOutput(RegionEndpoint rEndpoint)
        {
            StringBuilder sb = new StringBuilder(1024);

            using (StringWriter sr = new StringWriter(sb))
            {
                IAmazonSimpleDB simpleDBClient = new AmazonSimpleDBClient();

                try
                {
                    ListDomainsResponse response = simpleDBClient.ListDomains();
                    int numDomains = 0;
                    if (response.DomainNames != null &&
                        response.DomainNames.Count > 0)
                    {
                        numDomains = response.DomainNames.Count;
                    }
                    sr.WriteLine(string.Format("You have {0} Amazon SimpleDB domain(s) in the {1} region.",
                                               numDomains, rEndpoint.ToString()));
                    sr.WriteLine();
                    sr.WriteLine();
                    //S3Bucket[] domains = response.DomainNames.ToArray();
                    //foreach ( bucket in buckets)
                    //{
                    //    sr.WriteLine("--- " + bucket.BucketName.PadRight(63) + " --- " + bucket.CreationDate);
                    //}
                }
                catch (AmazonS3Exception ex)
                {
                    if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                                                 ex.ErrorCode.Equals("InvalidSecurity")))
                    {
                        sr.WriteLine("Please check the provided AWS Credentials.");
                        sr.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                    }
                }
            }

            return(sb.ToString());
        }
Example #12
0
        public override void ActivateOptions()
        {
            base.ActivateOptions();

            var  client   = new AmazonSimpleDBClient(Utility.GetRegionEndpoint());
            var  request  = new ListDomainsRequest();
            var  response = client.ListDomains(request);
            bool found    = response.ListDomainsResult.DomainNames.Any(d => d == DBName);

            if (!found)
            {
                var createDomainRequest =
                    new CreateDomainRequest
                {
                    DomainName = DBName
                };
                client.CreateDomain(createDomainRequest);
            }
        }
        public Dictionary <string, string> Get(string domainName, string itemName)
        {
            var client = new AmazonSimpleDBClient(
                new BasicAWSCredentials(
                    this.AccessKey,
                    this.SecretKey),
                this.RegionEndpoint);

            var unused1 = client.CreateDomainAsync(
                new CreateDomainRequest(
                    domainName)).Result;

            var result = client.GetAttributesAsync(
                new GetAttributesRequest(
                    domainName,
                    itemName)).Result;

            return(result.Attributes.ToDictionary(attr => attr.Name, attr => attr.Value));
        }
Example #14
0
        public bool CheckAuthentication(string userName, string password)
        {
            bool success = false;

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                SelectRequest request =
                    new SelectRequest().WithSelectExpression(string.Format("SELECT Id FROM Profiles where Username = '******' and Password='******'", userName, password));

                SelectResponse response = client.Select(request);
                if (response.SelectResult.Item.Count > 0)
                {
                    success           = true;
                    AuthenticatedUser = Guid.Parse(response.SelectResult.Item.First().Name);
                }
            }

            return(success);
        }
        public bool AddUpdateRoute(Route route)
        {
            bool success = true;

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                PutAttributesRequest request = new PutAttributesRequest
                {
                    DomainName = DomainName,
                    ItemName   = route.Id.ToString()
                };
                request.Attribute.Add(new ReplaceableAttribute()
                {
                    Name = "Name", Replace = true, Value = route.Name
                });
                request.Attribute.Add(new ReplaceableAttribute()
                {
                    Name = "Distance", Replace = true, Value = route.Distance.ToString()
                });
                request.Attribute.Add(new ReplaceableAttribute()
                {
                    Name = "Id", Replace = true, Value = route.Id.ToString()
                });
                request.Attribute.Add(new ReplaceableAttribute()
                {
                    Name = "LastTimeRidden", Replace = true, Value = route.LastTimeRidden.ToShortDateString()
                });
                request.Attribute.Add(new ReplaceableAttribute()
                {
                    Name = "Location", Replace = true, Value = route.Location
                });
                try
                {
                    PutAttributesResponse response = client.PutAttributes(request);
                }
                catch (Exception repositoryError)
                {
                    success = false;
                }
            }
            return(success);
        }
Example #16
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// </summary>
        /// <param name="disposing">Is disposing.</param>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!_disposed)
            {
                if (disposing)
                {
                    // Dispose managed state (managed objects).
                    if (_client != null)
                    {
                        _client.Dispose();
                    }
                }

                // Free unmanaged resources (unmanaged objects) and override a finalizer below.

                _disposed = true;
                _client   = null;
            }
        }
Example #17
0
        public Route GetRouteById(Guid routeId)
        {
            Route route = new Route();

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                SelectRequest request =
                    new SelectRequest().WithSelectExpression(
                        string.Format("SELECT * FROM Routes where Id = '{0}'", routeId));
                SelectResponse response = client.Select(request);

                if (response.SelectResult.Item.Count > 0)
                {
                    route.Id             = Guid.Parse(response.SelectResult.Item[0].Attribute.GetValueByName("Id"));
                    route.Distance       = response.SelectResult.Item[0].Attribute.GetDoubleValueByName("Distance");
                    route.LastTimeRidden = response.SelectResult.Item[0].Attribute.GetDateTimeValueByName("LastTimeRidden");
                }
            }
            return(route);
        }
Example #18
0
        public static void AddSampleData()
        {
            string domainName = String.Format(Settings.Default.SimpleDbDomainNameFormat, HttpContext.Current.User.Identity.Name);

            using (AmazonSimpleDBClient sdbClient = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USWest2))
            {
                using (AmazonS3Client s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2))
                {
                    foreach (Pet pet in pets)
                    {
                        string itemName = Guid.NewGuid().ToString();
                        pet.Put(domainName, itemName, true, sdbClient);
                        string   path       = HttpContext.Current.Server.MapPath("~/SampleData");
                        FileInfo file       = new FileInfo(Path.Combine(path, String.Concat(pet.Name.ToLowerInvariant().Replace(' ', '-'), ".jpg")));
                        string   bucketName = String.Format(Settings.Default.BucketNameFormat, HttpContext.Current.User.Identity.Name, itemName);
                        Pet.PutPhoto(domainName, itemName, bucketName, file.Name, file.OpenRead(), true, sdbClient, s3Client);
                    }
                }
            }
        }
Example #19
0
        public List <Route> GetUsersRoutes(Guid userId)
        {
            List <Route> list = new List <Route>();

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                SelectRequest request =
                    new SelectRequest().WithSelectExpression(
                        string.Format("SELECT RouteId FROM ProfileRoutes where ProfileId = '{0}'", userId));
                SelectResponse response = client.Select(request);
                foreach (Item routeItem in response.SelectResult.Item)
                {
                    list.Add(new Route()
                    {
                        Id = Guid.Parse(routeItem.Attribute.GetValueByName("RouteId"))
                    });
                }
            }

            return(list);
        }
Example #20
0
        public static bool CheckForDomains(string[] expectedDomains, AmazonSimpleDBClient sdbClient)
        {
            VerifyKeys();

            ListDomainsRequest  listDomainsRequest  = new ListDomainsRequest();
            ListDomainsResponse listDomainsResponse = sdbClient.ListDomains(listDomainsRequest);

            foreach (string expectedDomain in expectedDomains)
            {
                if (!listDomainsResponse.DomainNames.Contains(expectedDomain))
                {
                    // No point checking any more domains because
                    // at least 1 domain doesn't exist
                    return(false);
                }
            }

            // We got this far, indicating that all expectedDomains
            // were found in the domain list
            return(true);
        }
Example #21
0
        public Profile GetProfileById(Guid id)
        {
            Profile profile;

            using (AmazonSimpleDBClient client = new AmazonSimpleDBClient(_publicKey, _secretKey))
            {
                SelectRequest request =
                    new SelectRequest().WithSelectExpression(string.Format("SELECT * FROM Profiles where Id = '{0}'", id));

                SelectResponse response = client.Select(request);
                profile = (from item in response.SelectResult.Item
                           select new Profile()
                {
                    Id = Guid.Parse(item.Attribute.GetValueByName("Id")),
                    Description = item.Attribute.GetValueByName("Description"),
                    Location = item.Attribute.GetValueByName("Location"),
                    Name = item.Attribute.GetValueByName("Name")
                }).First();
            }
            return(profile);
        }
        public void Set(Dictionary <string, string> values, string domainName, string itemName)
        {
            var client = new AmazonSimpleDBClient(
                new BasicAWSCredentials(
                    this.AccessKey,
                    this.SecretKey),
                this.RegionEndpoint);

            var unused1 = client.CreateDomainAsync(
                new CreateDomainRequest(
                    domainName)).Result;

            var list = new AutoConstructedList <ReplaceableAttribute>();

            list.AddRange(
                values.Select(i => new ReplaceableAttribute(i.Key, i.Value, true)));

            var unused2 = client.PutAttributesAsync(
                new PutAttributesRequest(
                    domainName,
                    itemName,
                    list)).Result;
        }
Example #23
0
        public static void PutPhoto(string domainName, string itemName, string bucketName, string fileName, Stream fileContent, bool isPublic, AmazonSimpleDBClient sdbClient, AmazonS3Client s3Client)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                return;
            }

            BucketHelper.CheckForBucket(itemName, s3Client);

            PutObjectRequest putObjectRequest = new PutObjectRequest();

            putObjectRequest.BucketName  = bucketName;
            putObjectRequest.CannedACL   = S3CannedACL.PublicRead;
            putObjectRequest.Key         = fileName;
            putObjectRequest.InputStream = fileContent;
            s3Client.PutObject(putObjectRequest);

            DomainHelper.CheckForDomain(domainName, sdbClient);
            PutAttributesRequest putAttrRequest = new PutAttributesRequest()
            {
                DomainName = domainName,
                ItemName   = itemName
            };

            putAttrRequest.Attributes.Add(new ReplaceableAttribute
            {
                Name    = "PhotoThumbUrl",
                Value   = String.Format(Settings.Default.S3BucketUrlFormat, String.Format(Settings.Default.BucketNameFormat, HttpContext.Current.User.Identity.Name, itemName), fileName),
                Replace = true
            });
            sdbClient.PutAttributes(putAttrRequest);

            if (isPublic)
            {
                DomainHelper.CheckForDomain(Settings.Default.PetBoardPublicDomainName, sdbClient);
                putAttrRequest.DomainName = Settings.Default.PetBoardPublicDomainName;
                sdbClient.PutAttributes(putAttrRequest);
            }
        }
Example #24
0
        /// <summary>
        /// Sends the events.
        /// </summary>
        /// <param name="events">The events that need to be send.</param>
        /// <remarks>
        /// <para>
        /// The subclass must override this method to process the buffered events.
        /// </para>
        /// </remarks>
        protected override void SendBuffer(LoggingEvent[] events)
        {
            var client = new AmazonSimpleDBClient();

            Parallel.ForEach(events, e => UploadEvent(e, client));
        }
 public SimpleDBAssetPersistor(string awsAccessKeyId, string awsSecretAccessKey)
 {
     m_simpleDBClient = new AmazonSimpleDBClient(awsAccessKeyId, awsSecretAccessKey);
     m_objectMapper   = new ObjectMapper <T>();
 }
Example #26
0
        private void UploadEvent(LoggingEvent loggingEvent, AmazonSimpleDBClient client)
        {
            var request = new PutAttributesRequest();

            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Name    = "UserName",
                Replace = true,
                Value   = loggingEvent.UserName
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.TimeStamp.ToString(CultureInfo.InvariantCulture),
                Name    = "TimeStamp",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.ThreadName,
                Name    = "ThreadName",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.RenderedMessage,
                Name    = "Message",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.LoggerName,
                Name    = "LoggerName",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.Level.ToString(),
                Name    = "Level",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.Identity,
                Name    = "Identity",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = loggingEvent.Domain,
                Name    = "Domain",
                Replace = true
            });
            request.Attributes.Add(
                new ReplaceableAttribute
            {
                Value   = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
                Name    = "CreatedOn",
                Replace = true
            });
            request.DomainName = _dbName;
            request.ItemName   = Guid.NewGuid().ToString();

            client.PutAttributes(request);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "SimpleDbMembershipProvider";
            }

            base.Initialize(name, config);
            string tempFormat = config["passwordFormat"];

            if (tempFormat == null)
            {
                tempFormat = "Hashed";
            }

            switch (tempFormat)
            {
            case "Hashed":
            {
                this._passwordFormat = MembershipPasswordFormat.Hashed;
                break;
            }

            case "Encrypted":
            {
                this._passwordFormat = MembershipPasswordFormat.Encrypted;
                break;
            }

            case "Clear":
            {
                this._passwordFormat = MembershipPasswordFormat.Clear;
                break;
            }
            }

            this._simpleDBClient = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USWest2);

            CreateDomainRequest cdRequest = new CreateDomainRequest()
            {
                DomainName = Settings.Default.AWSMembershipDomain
            };

            try
            {
                this._simpleDBClient.CreateDomain(cdRequest);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Write(String.Concat(e.Message, "\r\n", e.StackTrace));
                this.VerifyKeys();
            }
            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);

            this._machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");
        }
Example #28
0
        internal AmazonSimpleDBClient GetClient()
        {
            AmazonSimpleDBClient client = new AmazonSimpleDBClient(_assessId, _secret, Amazon.RegionEndpoint.EUWest1);

            return(client);
        }
Example #29
0
        public static string GetServiceOutput()
        {
            StringBuilder sb = new StringBuilder(1024);

            using (StringWriter sr = new StringWriter(sb)) {
                sr.WriteLine("===========================================");
                sr.WriteLine("Welcome to the AWS .NET SDK!");
                sr.WriteLine("===========================================");

                // Print the number of Amazon EC2 instances.
                IAmazonEC2 ec2 = new AmazonEC2Client();
                DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();

                try {
                    DescribeInstancesResponse ec2Response = ec2.DescribeInstances(ec2Request);
                    int numInstances = 0;
                    numInstances = ec2Response.Reservations.Count;
                    sr.WriteLine(string.Format("You have {0} Amazon EC2 instance(s) running in the {1} region.",
                                               numInstances, ConfigurationManager.AppSettings["AWSRegion"]));
                } catch (AmazonEC2Exception ex) {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon EC2.");
                        sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                    }
                }
                sr.WriteLine();

                // Print the number of Amazon SimpleDB domains.
                IAmazonSimpleDB    sdb        = new AmazonSimpleDBClient();
                ListDomainsRequest sdbRequest = new ListDomainsRequest();

                try {
                    ListDomainsResponse sdbResponse = sdb.ListDomains(sdbRequest);

                    int numDomains = 0;
                    numDomains = sdbResponse.DomainNames.Count;
                    sr.WriteLine(string.Format("You have {0} Amazon SimpleDB domain(s) in the {1} region.",
                                               numDomains, ConfigurationManager.AppSettings["AWSRegion"]));
                } catch (AmazonSimpleDBException ex) {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB.");
                        sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                    }
                }
                sr.WriteLine();

                // Print the number of Amazon S3 Buckets.
                IAmazonS3 s3Client = new AmazonS3Client();

                try {
                    ListBucketsResponse response = s3Client.ListBuckets();
                    int numBuckets = 0;
                    if (response.Buckets != null &&
                        response.Buckets.Count > 0)
                    {
                        numBuckets = response.Buckets.Count;
                    }
                    sr.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s).");
                } catch (AmazonS3Exception ex) {
                    if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                                                 ex.ErrorCode.Equals("InvalidSecurity")))
                    {
                        sr.WriteLine("Please check the provided AWS Credentials.");
                        sr.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                    }
                }
                sr.WriteLine("Press any key to continue...");
            }
            return(sb.ToString());
        }
Example #30
0
        public void Put(string domainName, string itemName, bool isPublic, AmazonSimpleDBClient sdbClient)
        {
            if (String.IsNullOrEmpty(domainName) ||
                String.IsNullOrEmpty(itemName))
            {
                return;
            }

            DomainHelper.CheckForDomain(domainName, sdbClient);
            PutAttributesRequest putAttrRequest = new PutAttributesRequest()
            {
                DomainName = domainName,
                ItemName   = itemName
            };

            putAttrRequest.Attributes = new List <ReplaceableAttribute>()
            {
                new ReplaceableAttribute {
                    Name = "Public", Value = isPublic.ToString(), Replace = true
                },
                new ReplaceableAttribute {
                    Name = "PhotoThumbUrl", Value = !String.IsNullOrEmpty(this.PhotoThumbUrl) ? this.PhotoThumbUrl : String.Empty, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Name", Value = this.Name, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Type", Value = this.Type, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Breed", Value = this.Breed, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Sex", Value = this.Sex, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Birthdate", Value = this.Birthdate, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Likes", Value = this.Likes, Replace = true
                },
                new ReplaceableAttribute {
                    Name = "Dislikes", Value = this.Dislikes, Replace = true
                }
            };
            sdbClient.PutAttributes(putAttrRequest);

            if (isPublic)
            {
                DomainHelper.CheckForDomain(Settings.Default.PetBoardPublicDomainName, sdbClient);
                putAttrRequest.DomainName = Settings.Default.PetBoardPublicDomainName;
                sdbClient.PutAttributes(putAttrRequest);
            }
            else
            {
                DeleteAttributesRequest deleteAttributeRequest = new DeleteAttributesRequest()
                {
                    DomainName = Settings.Default.PetBoardPublicDomainName,
                    ItemName   = itemName
                };

                sdbClient.DeleteAttributes(deleteAttributeRequest);
            }
        }