public static bool CheckForDomains(string[] expectedDomains, AmazonSimpleDBClient sdbClient) { VerifyKeys(); ListDomainsRequest listDomainsRequest = new ListDomainsRequest(); ListDomainsResponse listDomainsResponse = sdbClient.ListDomains(listDomainsRequest); if (listDomainsResponse.IsSetListDomainsResult()) { ListDomainsResult result = listDomainsResponse.ListDomainsResult; foreach (string expectedDomain in expectedDomains) { if (!result.DomainName.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; } // No results were returned by the ListDomains call // or something else went wrong return false; }
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; }
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().WithSelectExpression(String.Format("select * from `{0}`", this._domainName)); SelectResponse selectResponse = sdbClient.Select(selectRequest); List<Item> items = selectResponse.SelectResult.Item; List<Pet> pets = items.Select(l => new Pet { Id = l.Name, PhotoThumbUrl = l.Attribute.First(a => a.Name == "PhotoThumbUrl").Value, Name = l.Attribute.First(a => a.Name == "Name").Value, Birthdate = l.Attribute.First(a => a.Name == "Birthdate").Value, Sex = l.Attribute.First(a => a.Name == "Sex").Value, Type = l.Attribute.First(a => a.Name == "Type").Value, Breed = l.Attribute.First(a => a.Name == "Breed").Value }).ToList(); this.PetRepeater.DataSource = pets; this.PetRepeater.DataBind(); } } }
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; }
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; }
public Default() { if (_simpleDBClient == null) { _simpleDBClient = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USWest2); } System.Threading.Thread.MemoryBarrier(); }
public PetProfile() { if (_simpleDBClient == null) { _simpleDBClient = new AmazonSimpleDBClient( Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim() ); } System.Threading.Thread.MemoryBarrier(); }
public SimpleDBStorage () { var credentials = new CognitoAWSCredentials ( Constants.CognitoIdentityPoolId, RegionEndpoint.USEast1); var config = new AmazonSimpleDBConfig (); config.RegionEndpoint = RegionEndpoint.USWest2; client = new AmazonSimpleDBClient (credentials, config); Items = new List<TodoItem> (); SetupDomain (); }
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); }
public static List<Tags> GetTags(string domainName, AmazonSimpleDBClient sdbClient) { List<Tags> tagses = new List<Tags>(); Tags tags; String selectExpression = "Select TagId,TagName,Country From " + domainName; SelectRequest selectRequestAction = new SelectRequest().WithSelectExpression(selectExpression); SelectResponse selectResponse = sdbClient.Select(selectRequestAction); if (selectResponse.IsSetSelectResult()) { SelectResult selectResult = selectResponse.SelectResult; foreach (Item item in selectResult.Item) { tags = new Tags(); ; if (item.IsSetName()) { } int i = 0; foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attribute) { if (attribute.IsSetName()) { string name = attribute.Name; } if (attribute.IsSetValue()) { switch (attribute.Name) { case "TagId": tags.TagId = Guid.Parse(attribute.Value); break; case "TagName": tags.TagName = attribute.Value; break; case "Country": tags.Country = attribute.Value; break; } i++; } } tagses.Add(tags); } } return tagses; }
public SimpleDBAppender() { var client = new AmazonSimpleDBClient(); ListDomainsRequest request=new ListDomainsRequest(); var response = client.ListDomains(request); bool found = response.ListDomainsResult.DomainName.Any(d => d == DBName); if (!found) { CreateDomainRequest createDomainRequest = new CreateDomainRequest { DomainName = DBName }; client.CreateDomain(createDomainRequest); } }
private int maxItemsPerRequest = 25; // simpledb has max 25 items per batch put request #endregion Fields #region Methods protected override void SendBuffer(log4net.Core.LoggingEvent[] events) { var client = new AmazonSimpleDBClient(); // access and secret keys in web.config for (var i = 0; i < (events.Count() / maxItemsPerRequest) + 1; i++) { try { var request = new BatchPutAttributesRequest(); foreach (var e in events.Skip(i * maxItemsPerRequest).Take(maxItemsPerRequest)) { var batchItem = new ReplaceableItem() { ItemName = Guid.NewGuid().ToString() }; batchItem.Attribute.Add(GetAttribute("Thread", e.ThreadName)); batchItem.Attribute.Add(GetAttribute("Level", e.Level.Name)); batchItem.Attribute.Add(GetAttribute("CustomLevel", GetCustomProperty(e, "CustomLevel"))); batchItem.Attribute.Add(GetAttribute("Url", GetCustomProperty(e, "Url"))); batchItem.Attribute.Add(GetAttribute("Machine", GetCustomProperty(e, "Machine"))); batchItem.Attribute.Add(GetAttribute("Product", GetCustomProperty(e, "Product"))); batchItem.Attribute.Add(GetAttribute("UserId", GetCustomProperty(e, "UserId"))); batchItem.Attribute.Add(GetAttribute("UserName", GetCustomProperty(e, "UserName"))); batchItem.Attribute.Add(GetAttribute("TimeStamp", e.TimeStamp.ToUniversalTime().ToString("o"))); batchItem.Attribute.Add(GetAttribute("Message", e.RenderedMessage)); batchItem.Attribute.Add(GetAttribute("FormattedMessage", GetCustomProperty(e, "FormattedMessage"))); batchItem.Attribute.Add(GetAttribute("StackTrace", e.GetExceptionString())); request.Item.Add(batchItem); } // Assumes Domain has already been created if(!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SimpleDBLogName"])) request.DomainName = ConfigurationManager.AppSettings["SimpleDBLogName"]; else request.DomainName = "Log"; client.BatchPutAttributes(request); } finally { } } }
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 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; }
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 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; }
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 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.WithBucketName(bucketName); putObjectRequest.CannedACL = S3CannedACL.PublicRead; putObjectRequest.Key = fileName; putObjectRequest.InputStream = fileContent; S3Response response = s3Client.PutObject(putObjectRequest); response.Dispose(); DomainHelper.CheckForDomain(domainName, sdbClient); PutAttributesRequest putAttrRequest = new PutAttributesRequest() .WithDomainName(domainName) .WithItemName(itemName); putAttrRequest.WithAttribute(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); } }
public static void AddSampleData() { string domainName = String.Format(Settings.Default.SimpleDbDomainNameFormat, HttpContext.Current.User.Identity.Name); using (AmazonSimpleDBClient sdbClient = new AmazonSimpleDBClient(Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim())) { using (AmazonS3Client s3Client = new AmazonS3Client(Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim())) { 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); } } } }
public static List<NewsComponents> GetNewsStories(string domainName, AmazonSimpleDBClient sdbClient) { List<NewsComponents> newsItems = new List<NewsComponents>(); NewsComponents newsItem = null; String selectExpression = "Select NewsID,Source,Section,Publish,NewsHeadline,NewsAdded,Photos,Summary,Category From " + domainName; SelectRequest selectRequestAction = new SelectRequest().WithSelectExpression(selectExpression); SelectResponse selectResponse = sdbClient.Select(selectRequestAction); if (selectResponse.IsSetSelectResult()) { SelectResult selectResult = selectResponse.SelectResult; foreach (Item item in selectResult.Item) { newsItem = new NewsComponents(); if (item.IsSetName()) { } int i = 0; foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attribute) { if (attribute.IsSetName()) { string name = attribute.Name; } if (attribute.IsSetValue()) { switch (attribute.Name) { case "NewsID": newsItem.NewsID = Guid.Parse(attribute.Value); break; case "Source": newsItem.Source = attribute.Value; break; case "Section": newsItem.Section = attribute.Value; break; case "NewsItem": newsItem.NewsItem = attribute.Value; break; case "NewsHeadline": newsItem.NewsHeadline = attribute.Value; break; case "Publish": newsItem.Publish = Convert.ToBoolean(attribute.Value); break; case "NewsAdded": newsItem.NewsAdded = Convert.ToDateTime(attribute.Value); break; case "Photos": newsItem.NewsPhotoUrl = attribute.Value; break; case "Summary": newsItem.NewsItem = GetTheHtml(attribute.Value); break; case "Category": newsItem.Category = attribute.Value; break; case "SummaryContent": newsItem.SummaryContent = attribute.Value; break; } i++; } } newsItems.Add(newsItem); } } return newsItems; }
public Proxy() { PublicKey = ConfigurationManager.AppSettings["PublicKey"]; SecretKey = ConfigurationManager.AppSettings["SecretKey"]; Service = new AmazonSimpleDBClient(PublicKey, SecretKey); }
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 static NewsComponents GetNewsItem(string domainName, string itemName, AmazonSimpleDBClient sdbClient) { NewsComponents newsItem = new NewsComponents(); GetAttributesRequest getAttributeRequest = new GetAttributesRequest() .WithDomainName(domainName) .WithItemName(itemName); GetAttributesResponse getAttributeResponse = sdbClient.GetAttributes(getAttributeRequest); List<Amazon.SimpleDB.Model.Attribute> attrs = null; if (getAttributeResponse.IsSetGetAttributesResult()) { attrs = getAttributeResponse.GetAttributesResult.Attribute; int i = 0; foreach (Amazon.SimpleDB.Model.Attribute attribute in attrs) { if (attribute.IsSetName()) { string name = attribute.Name; } if (attribute.IsSetValue()) { switch (i) { case 0: newsItem.NewsID = Guid.Parse(attribute.Value); break; case 1: newsItem.Source = attribute.Value; break; case 2: newsItem.Section = attribute.Value; break; case 3: newsItem.NewsItem = attribute.Value; break; case 4: newsItem.NewsHeadline = attribute.Value; break; case 5: newsItem.NewsAdded = Convert.ToDateTime(attribute.Value); break; case 7: newsItem.Summary = attribute.Value; break; case 8: newsItem.Category = attribute.Value; break; } i++; } } } return newsItem; }
/// <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 static void SaveNewItems(string domainName, string bucketName, NewsComponents newsItem, AmazonSimpleDBClient sdbClient, AmazonS3Client s3Client) { try { foreach (var stream in newsItem.Images) { PutObjectRequest putObjectRequest = new PutObjectRequest(); putObjectRequest.WithBucketName(bucketName); putObjectRequest.CannedACL = S3CannedACL.PublicRead; putObjectRequest.Key = stream.fileName; putObjectRequest.InputStream = stream.photostreams; using (S3Response response = s3Client.PutObject(putObjectRequest)) { WebHeaderCollection headers = response.Headers; foreach (string key in headers.Keys) { //log headers ("Response Header: {0}, Value: {1}", key, headers.Get(key)); } } } PutObjectRequest putObjectNewsItem = new PutObjectRequest(); putObjectNewsItem.WithBucketName(newsItem.BucketName); putObjectNewsItem.CannedACL = S3CannedACL.PublicRead; putObjectNewsItem.Key = Convert.ToString(newsItem.NewsID); putObjectNewsItem.ContentType = "text/html"; putObjectNewsItem.ContentBody = newsItem.NewsItem; using (S3Response response = s3Client.PutObject(putObjectNewsItem)) { WebHeaderCollection headers = response.Headers; foreach (string key in headers.Keys) { //log headers ("Response Header: {0}, Value: {1}", key, headers.Get(key)); } } PutAttributesRequest putAttrRequest = new PutAttributesRequest() .WithDomainName(domainName) .WithItemName(Convert.ToString(newsItem.NewsID)); putAttrRequest.WithAttribute( new ReplaceableAttribute { Name = "NewsID", Value = Convert.ToString(newsItem.NewsID), Replace = false }, new ReplaceableAttribute { Name = "Source", Value = newsItem.Source, Replace = false }, new ReplaceableAttribute { Name = "NewsHeadline", Value = newsItem.NewsHeadline, Replace = true }, new ReplaceableAttribute { Name = "NewsAdded", Value = Convert.ToString(newsItem.NewsAdded), Replace = true } , new ReplaceableAttribute { Name = "Summary", Value = newsItem.Summary, Replace = true } , new ReplaceableAttribute { Name = "SummaryContent", Value = newsItem.SummaryContent, Replace = true } , new ReplaceableAttribute { Name = "Imagelabel", Value = newsItem.Imagelabel, Replace = true }, new ReplaceableAttribute { Name = "Photos", Value = newsItem.NewsPhotoUrl, Replace = true } , new ReplaceableAttribute { Name = "Category", Value = newsItem.Category, Replace = true } , new ReplaceableAttribute { Name = "TimeStamp", Value = Convert.ToString(newsItem.TimeStamp), Replace = true }); sdbClient.PutAttributes(putAttrRequest); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { //log exception - ("Please check the provided AWS Credentials."); } else { //log exception -("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message); } } catch (AmazonSimpleDBException amazonSimpleDBException) { string val = amazonSimpleDBException.ErrorCode; } }
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(); }
/// <summary> /// Helper method to write an object graph dump to the configured domain /// </summary> /// <param name="state"></param> private void WriteObjectAsync(Object state) { try { Object o = ((Object[])state)[0]; String category = (String)((Object[])state)[1]; String message = GetObjectDump(o); using (AmazonSimpleDBClient client = new AmazonSimpleDBClient( this.AWSAccessKey, this.AWSSecretAccessKey, new AmazonSimpleDBConfig() { ServiceURL = this.AWSServiceUrl, MaxErrorRetry = 20 })) { String[] messages = StringSplitByLength(message, 1024); PutAttributesRequest request = new PutAttributesRequest(); request.DomainName = this.DomainName; request.ItemName = Guid.NewGuid().ToString(); for (int i = 0; i < messages.Length; i++) { request.Attribute.Add(new ReplaceableAttribute() { Name = "Message" + i.ToString(), Value = messages[i] }); } request.Attribute.Add(new ReplaceableAttribute() { Name = "Category", Value = category }); client.PutAttributes(request); } } catch (Exception ex) { TryWriteEventLogEntry(ex); } }
/// <summary> /// Helper method to write a LogEntry to the configured domain /// </summary> /// <param name="entry"></param> private void WriteLogEntryAsync(Object state) { try { LogEntry entry = (LogEntry)state; using (AmazonSimpleDBClient client = new AmazonSimpleDBClient( this.AWSAccessKey, this.AWSSecretAccessKey, new AmazonSimpleDBConfig() { ServiceURL = this.AWSServiceUrl, MaxErrorRetry = 20 })) { PutAttributesRequest request = new PutAttributesRequest(); request.DomainName = this.DomainName; // make the key the ActivityId_Guid or just a Guid if (!String.IsNullOrEmpty(entry.ActivityIdString)) { request.ItemName = entry.ActivityIdString + "_" + Guid.NewGuid().ToString(); } else { request.ItemName = Guid.NewGuid().ToString(); } // add the categories if ((entry.CategoriesStrings != null) && (entry.CategoriesStrings.Length > 0)) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < entry.CategoriesStrings.Length; i++) { if (i != 0) { sb.Append("_"); } sb.Append(entry.CategoriesStrings[i]); } request.Attribute.Add(new ReplaceableAttribute() { Name = "Categories", Value = sb.ToString() }); } // add the error message if there is one if (!String.IsNullOrEmpty(entry.ErrorMessages)) { request.Attribute.Add(new ReplaceableAttribute() { Name = "ErrorMessages", Value = entry.ErrorMessages }); } foreach (KeyValuePair<String, Object> kvp in entry.ExtendedProperties) { request.Attribute.Add(new ReplaceableAttribute() { Name = kvp.Key, Value = kvp.Value.ToString() }); } if (!String.IsNullOrEmpty(entry.LoggedSeverity)) { request.Attribute.Add(new ReplaceableAttribute() { Name = "LoggedSeverity", Value = entry.LoggedSeverity }); } if (!String.IsNullOrEmpty(entry.MachineName)) { request.Attribute.Add(new ReplaceableAttribute() { Name = "MachineName", Value = entry.MachineName }); } // need to handle if the message is greater than 1024 chars for simple db String[] messages = StringSplitByLength(entry.Message, 1024); for (int i = 0; i < messages.Length; i++) { request.Attribute.Add(new ReplaceableAttribute() { Name = "Message" + i.ToString(), Value = messages[i] ?? String.Empty }); } request.Attribute.Add(new ReplaceableAttribute() { Name = "Priority", Value = entry.Priority.ToString() }); request.Attribute.Add(new ReplaceableAttribute() { Name = "ProcessName", Value = entry.ProcessName ?? String.Empty }); request.Attribute.Add(new ReplaceableAttribute() { Name = "Severity", Value = entry.Severity.ToString() }); request.Attribute.Add(new ReplaceableAttribute() { Name = "TimeStamp", Value = entry.TimeStampString ?? DateTime.UtcNow.ToString() }); if (!String.IsNullOrEmpty(entry.Title)) { request.Attribute.Add(new ReplaceableAttribute() { Name = "Title", Value = entry.Title ?? String.Empty }); } client.PutAttributes(request); } } catch (Exception ex) { TryWriteEventLogEntry(ex); } }
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( Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim() ); CreateDomainRequest cdRequest = new CreateDomainRequest() .WithDomainName(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"); }
public static void SaveVideoItems(string domainName, Multimedia videoItem, AmazonSimpleDBClient sdbClient) { try { PutAttributesRequest putVideoRequest = new PutAttributesRequest() .WithDomainName(domainName) .WithItemName(Convert.ToString(videoItem.VideoId)); putVideoRequest.WithAttribute( new ReplaceableAttribute { Name = "VideoId", Value = Convert.ToString(videoItem.VideoId), Replace = false }, new ReplaceableAttribute { Name = "YoutubeUrl", Value = videoItem.YoutubeUrl, Replace = false }, new ReplaceableAttribute { Name = "Country", Value = videoItem.Country, Replace = true }, new ReplaceableAttribute { Name = "Title", Value = Convert.ToString(videoItem.Title), Replace = true } , new ReplaceableAttribute { Name = "Content", Value = videoItem.Content, Replace = true }); sdbClient.PutAttributes(putVideoRequest); } catch (AmazonSimpleDBException amazonSimpleDBException) { string val = amazonSimpleDBException.ErrorCode; } }