// POST api/values public async Task Post([FromBody] Usuario usuario) { using (var repos = new DynamoDBHelper(awsAccessKey, AWSSecretKey, ServiceUrl)) { await repos.Save <Usuario>(usuario); } }
public async static Task <bool> AddNotes(NotesContent notes) { NotesStructure notesStructure = new NotesStructure(); notesStructure.Notes[Constants.USER_ID] = notes.UserId; notesStructure.Notes[Constants.TIMESTAMP] = notes.TimeStamp; notesStructure.Notes[Constants.NOTES_TEXT] = notes.NotesText; notesStructure.Notes[Constants.NOTES_TITLE] = notes.NotesTitle; if (!string.IsNullOrEmpty(notes.FilePath)) { string keyName = ""; if (!UploadFileToS3(notes.UserId, notes.FilePath, out keyName)) { Logger.AddLog("Failed to upload file to S3"); return(false); } notesStructure.Notes[Constants.FILE] = keyName; } var insertResult = DynamoDBHelper.Instance().InsertNotes(notesStructure); if (insertResult) { Logger.AddLog("Successfully added notes"); } else { Logger.AddLog("Failed to added notes"); } return(insertResult); }
public async Task TableCreationShouldGoThru() { var options = new DynamoDBProviderOptions("proto_actor_events", "proto_actor_snapshots"); await DynamoDBHelper.CheckCreateEventsTable(_client, options, 1, 1); await DynamoDBHelper.CheckCreateSnapshotsTable(_client, options, 1, 1); }
public static List <NotesContent> FetchNotes(string userId) { List <NotesContent> fetchedNotes = new List <NotesContent>(); var rsp = DynamoDBHelper.Instance().FetchNotes(userId); foreach (var notes in rsp) { NotesContent content = new NotesContent(null); content.UserId = notes.Notes[Constants.USER_ID]; content.TimeStamp = notes.Notes[Constants.TIMESTAMP]; content.NotesText = notes.Notes[Constants.NOTES_TEXT]; if (notes.Notes.ContainsKey(Constants.NOTES_TITLE)) { content.NotesTitle = notes.Notes[Constants.NOTES_TITLE]; } if (notes.Notes.ContainsKey(Constants.FILE)) { content.FilePath = notes.Notes[Constants.FILE]; } fetchedNotes.Add(content); } return(fetchedNotes); }
private static void InitializeS3() { var bucketName = DynamoDBHelper.Instance().FetchMetadata(Constants.TOP_LEVEL_BUCKET_NAME_METADATA_KEY); if (string.IsNullOrEmpty(bucketName)) // The bucket doesnt exist yet, create it now { bool bucketCreated = false; do { var hashValue = Math.Abs(DateTime.Now.ToString().GetHashCode()); var newBucketName = Constants.APPNAME + hashValue.ToString(); newBucketName = newBucketName.ToLower(); bucketCreated = S3Helper.Instance().CreateS3Bucket(newBucketName); if (bucketCreated) { UpdateMetadataWithS3BucketName(newBucketName); } var thumbnailBucketName = newBucketName + "-thumbnails"; bucketCreated = S3Helper.Instance().CreateS3Bucket(thumbnailBucketName); if (bucketCreated) { UpdateMetadataWithS3ThumbailBucketName(thumbnailBucketName); } }while (bucketCreated == false); } else { Console.WriteLine("Required S3 buckets already exist, not creating new ones now"); } }
// DELETE api/values/5 public async Task Delete(string id) { using (var repos = new DynamoDBHelper(awsAccessKey, AWSSecretKey, ServiceUrl)) { var response = repos.Load <Usuario>(id); await repos.Delete <Usuario>(response); } }
// GET api/values/5 public Usuario Get(string id) { var repos = new DynamoDBHelper(awsAccessKey, AWSSecretKey, ServiceUrl); var response = repos.Load <Usuario>(id); return(response); }
public async Task <bool> DeleteAsync(IEnumerable <TEntity> items) { foreach (var item in items) { await DynamoDBHelper.AttemptOperation(async() => await this.DataContext.DeleteAsync(item)); } return(true); }
public async Task <IList <Usuario> > Get() { var repos = new DynamoDBHelper(awsAccessKey, AWSSecretKey, ServiceUrl); var response = await repos.GetRows <Usuario>(new List <ScanCondition>()); return(response); }
public async Task <Usuario> GetByEmail([FromUri] string email) { var repos = new DynamoDBHelper(awsAccessKey, AWSSecretKey, ServiceUrl); List <ScanCondition> conditions = new List <ScanCondition>(); conditions.Add(new ScanCondition("email", Amazon.DynamoDBv2.DocumentModel.ScanOperator.Equal, email)); var response = await repos.GetRows <Usuario>(conditions); return(response.FirstOrDefault()); }
// PUT api/values/5 public async Task Put(string id, [FromBody] Usuario usuario) { using (var repos = new DynamoDBHelper(awsAccessKey, AWSSecretKey, ServiceUrl)) { var response = repos.Load <Usuario>(id); response.Nome = usuario.Nome != null? usuario.Nome: response.Nome; response.email = usuario.email != null ? usuario.email : response.email; response.Nivel = usuario.Nivel != null ? usuario.Nivel : response.Nivel; response.DataNascimento = usuario.DataNascimento != DateTime.MinValue? usuario.DataNascimento : response.DataNascimento; response.Documento = usuario.Documento != null ? usuario.Documento : response.Documento; await repos.Save <Usuario>(response); } }
// [OneTimeSetUp] public async Task CreateTableAndIndexes() { await DynamoDBHelper.DeleteTable("GameScores"); var gsi = new GlobalSecondaryIndex() { IndexName = "GameTitleIndex", KeySchema = new List <KeySchemaElement>() { new KeySchemaElement("GameTitle", KeyType.HASH), new KeySchemaElement("TopScore", KeyType.RANGE) }, Projection = new Projection() { ProjectionType = ProjectionType.ALL, }, ProvisionedThroughput = new ProvisionedThroughput(2, 2) }; var request = new CreateTableRequest() { TableName = "GameScores", AttributeDefinitions = new List <AttributeDefinition>() { new AttributeDefinition("UserId", ScalarAttributeType.S), new AttributeDefinition("GameTitle", ScalarAttributeType.S), new AttributeDefinition("TopScore", ScalarAttributeType.N) }, KeySchema = new List <KeySchemaElement>() { new KeySchemaElement("UserId", KeyType.HASH), new KeySchemaElement("GameTitle", KeyType.RANGE) }, ProvisionedThroughput = new ProvisionedThroughput(2, 2), GlobalSecondaryIndexes = { gsi }, BillingMode = BillingMode.PROVISIONED }; var result = await DynamoDBHelper.Client.CreateTableAsync(request); await DynamoDBHelper.WaitUntilTableReady("GameScores"); var batchResult = await PutItemsBatch(CreateTableItems()); var results = await PutItems(CreateTableItems()); var results1 = await PutItems(CreateTableItems()); }
public override IDataReader ExecuteReader(ServiceCursorDef cursorDef, IDataParameterCollection parms, CommandBehavior behavior) { Initialize(); Query query = cursorDef.Query as Query; Dictionary <string, AttributeValue> valuesAux = new Dictionary <string, AttributeValue>(); Dictionary <string, AttributeValue> values = new Dictionary <string, AttributeValue>(); if (parms.Count > 0) { for (int i = 0; i < parms.Count; i++) { ServiceParameter parm = parms[i] as ServiceParameter; DynamoDBHelper.GXToDynamoQueryParameter(":", values, parm); } } List <string> filtersAux = new List <string>(); List <string> filters = new List <string>(); filters.AddRange(query.Filters); foreach (var item in query.Vars) { values.Add(item.Name, DynamoDBHelper.ToAttributeValue(item)); } try { DynamoDBDataReader dataReader; AmazonDynamoDBRequest req; CreateDynamoQuery(query, values, filters.ToArray(), out dataReader, out req); RequestWrapper reqWrapper = new RequestWrapper(mDynamoDB, req); dataReader = new DynamoDBDataReader(cursorDef, reqWrapper, parms); return(dataReader); } catch (AmazonDynamoDBException e) { throw e; } catch (AmazonServiceException e) { throw e; } catch (Exception e) { throw e; } }
/// <summary> /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public void ProcessS3Events(S3Event evnt, ILambdaContext context) { string tableName; if (isLocalDebug) { tableName = "pwc-filelogtable"; } else { tableName = System.Environment.GetEnvironmentVariable("DynamoDBTableName"); } DynamoDBHelper dynamoObj = new DynamoDBHelper(context, tableName, isLocalDebug); var s3Event = evnt.Records?[0].S3; try { if (s3Event != null) { context.Logger.LogLine($"DynamoDB TableName = {tableName}."); KeyDBItem newItem = new KeyDBItem(); newItem.Timestamp = DateTime.Now.ToString(); newItem.FileName = s3Event.Object.Key; dynamoObj.putItem(newItem, tableName); } } catch (Exception e) { context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function."); context.Logger.LogLine(e.Message); context.Logger.LogLine(e.StackTrace); throw; } }
private static void UpdateMetadataWithS3BucketName(string newBucketName) { DynamoDBHelper.Instance().InsertMetadata(Constants.TOP_LEVEL_BUCKET_NAME_METADATA_KEY, newBucketName); }
private static void UpdateMetadataWithS3ThumbailBucketName(string thumbnailBucketName) { DynamoDBHelper.Instance().InsertMetadata(Constants.TOP_LEVEL_THUMBNAIL_BUCKET_NAME_METADATA_KEY, thumbnailBucketName); }
public static string GetBucketName() { return(DynamoDBHelper.Instance().FetchMetadata(Constants.TOP_LEVEL_BUCKET_NAME_METADATA_KEY)); }
public LogDb() { helper = new DynamoDBHelper <Log>(); }
public async Task <bool> DeleteAsync(TEntity item) { await DynamoDBHelper.AttemptOperation(async() => await this.DataContext.DeleteAsync(item)); return(true); }
public async Task <TEntity> GetByIdAsync(TKey id) { return((await DynamoDBHelper.AttemptOperation(async() => await this.DataContext.QueryAsync <TEntity>(id).GetNextSetAsync())).FirstOrDefault()); }
public async Task <ICollection <TEntity> > GetAllAsync() { var coniditions = new List <ScanCondition>(); return(await DynamoDBHelper.AttemptOperation(async() => await this.DataContext.ScanAsync <TEntity>(coniditions).GetRemainingAsync())); }
public override int ExecuteNonQuery(ServiceCursorDef cursorDef, IDataParameterCollection parms, CommandBehavior behavior) { Initialize(); Query query = cursorDef.Query as Query; Dictionary <string, AttributeValue> values = new Dictionary <string, AttributeValue>(); if (parms.Count > 0) { for (int i = 0; i < parms.Count; i++) { ServiceParameter parm = parms[i] as ServiceParameter; DynamoDBHelper.GXToDynamoQueryParameter("", values, parm); } } var pattern = @"\((.*) = :(.*)\)"; Dictionary <string, AttributeValue> keyCondition = new Dictionary <string, AttributeValue>(); List <string> filters = new List <string>(); foreach (var keyFilter in query.Filters) { var match = Regex.Match(keyFilter, pattern); String varName = match.Groups[2].Value; if (match.Groups.Count > 1) { keyCondition[match.Groups[1].Value] = values[varName]; } } AmazonDynamoDBRequest request = null; switch (query.CursorType) { case ServiceCursorDef.CursorType.Select: throw new NotImplementedException(); case ServiceCursorDef.CursorType.Delete: request = new DeleteItemRequest() { TableName = query.TableName, Key = keyCondition }; mDynamoDB.DeleteItem((DeleteItemRequest)request); break; case ServiceCursorDef.CursorType.Insert: request = new PutItemRequest { TableName = query.TableName, Item = values }; mDynamoDB.PutItem((PutItemRequest)request); break; case ServiceCursorDef.CursorType.Update: request = new UpdateItemRequest { TableName = query.TableName, Key = keyCondition, AttributeUpdates = ToAttributeUpdates(keyCondition, values) }; mDynamoDB.UpdateItem((UpdateItemRequest)request); break; default: break; } return(0); }
public CloudFormationResponse LoadMasterData(LoadMasterDataCustomCloudformationEvent request, ILambdaContext context) { try { string UniqueIdGenerated = SecurityHelper.GetSha256Hash($"{request.StackId}:{request.LogicalResourceId}"); DynamoDBMasterItem1 item1 = new DynamoDBMasterItem1( UniqueIdGenerated, Convert.ToString(Guid.NewGuid()), "Rohit Srivastava", "Senior Consultant", "29", "Advisory"); context.Logger.LogLine($"Input event invoked: {JsonConvert.SerializeObject(request)}"); DynamoDBHelper dynamoDBHelper = new DynamoDBHelper(context, this.isLocalDebug); context.Logger.LogLine($"Custom cloudformation event request type: {request.RequestType}"); //Since this is not basically creation of any custom resource , rather initial data load , we donot need //to care about anything other than the CREATE request type if (string.Equals(request.RequestType, Constants.CloudFormationCreateRequestType)) { dynamoDBHelper.putItemTable1(item1, request.ResourceProperties.TableName); //Success - data inserted properly in the dynamoDB CloudFormationResponse objResponse = new CloudFormationResponse( Constants.CloudformationSuccessCode, "Custom Resource Creation Successful", $"{request.StackId}-{request.LogicalResourceId}-DataLoad", request.StackId, request.RequestId, request.LogicalResourceId, item1 ); return(objResponse.CompleteCloudFormationResponse(request, context).GetAwaiter().GetResult()); } else { CloudFormationResponse objResponse = new CloudFormationResponse( Constants.CloudformationSuccessCode, "Do nothing.Data will be pushed in only when stack event is Create", context.LogStreamName, request.StackId, request.RequestId, request.LogicalResourceId, null ); return(objResponse.CompleteCloudFormationResponse(request, context).GetAwaiter().GetResult()); } } catch (Exception ex) { context.Logger.LogLine($"StartupProgram::LoadMasterData => {ex.Message}"); context.Logger.LogLine($"StartupProgram::LoadMasterData => {ex.StackTrace}"); //Error - log it into the cloudformation console CloudFormationResponse objResponse = new CloudFormationResponse( Constants.CloudformationErrorCode, ex.Message, context.LogStreamName, request.StackId, request.RequestId, request.LogicalResourceId, null ); return(objResponse.CompleteCloudFormationResponse(request, context).GetAwaiter().GetResult()); } }
public AutoScaleGroupSettingsDb() { helper = new DynamoDBHelper <AutoScalingGroupSettings>(); }
public EnvironmentAccountDb() { helper = new DynamoDBHelper <EnvironmentAccount>(); }