public async Task ScanByConditions() { Console.WriteLine("Grab all items where name starts with 'Mi': "); List <Profile> profiles = await _context.ScanAsync <Profile>(new[] { new ScanCondition(nameof(Profile.Name), ScanOperator.BeginsWith, "Mi") }).GetRemainingAsync(); IterateList(profiles); Console.WriteLine("\n\nGrab all items where email in ('*****@*****.**','*****@*****.**','*****@*****.**'): "); ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition(nameof(Profile.Email), ScanOperator.In, "*****@*****.**", "*****@*****.**", "*****@*****.**"); profiles = await _context.FromScanAsync <Profile>(new ScanOperationConfig { Filter = scanFilter }).GetRemainingAsync(); IterateList(profiles); }
public List <InteractionModel> GetCommands() { AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig { RegionEndpoint = RegionEndpoint.USEast1 }; AmazonDynamoDBClient client = new AmazonDynamoDBClient(ddbConfig); string tableName = "draniki-alexa-commands"; Table commandsTable = Table.LoadTable(client, tableName); ScanFilter scanFilter = new ScanFilter(); ScanOperationConfig config = new ScanOperationConfig { Filter = scanFilter, Select = SelectValues.AllAttributes }; Search search = commandsTable.Scan(config); List <Document> documentList; List <InteractionModel> interactions = new List <InteractionModel>(); do { documentList = search.GetNextSet(); foreach (var document in documentList) { var jsonObject = document.ToJsonPretty(); var objectModel = JsonConvert.DeserializeObject <InteractionModel>(jsonObject); interactions.Add(objectModel); } }while (!search.IsDone); return(interactions); }
public void CommandSubscribe() { Table replyTable = Table.LoadTable(client, tableName); Console.WriteLine("Listening to the events continuously."); Int64 last_key = 0; while (true) { var scan_filter = new ScanFilter(); if (last_key > 0) { scan_filter.AddCondition("K", ScanOperator.GreaterThan, last_key); } Search search = replyTable.Scan(scan_filter); List <Document> documentList = new List <Document>(); do { documentList = search.GetNextSet(); foreach (var document in documentList) { Console.WriteLine("{0} : {1}", document["K"], document["V"]); Int64 current_key = Int64.Parse(document["K"].AsString()); if (!(current_key > last_key)) { Console.WriteLine("ERROR: {0} should be > {1}.", current_key, last_key); } else { last_key = current_key; } } } while (!search.IsDone); // TODO(dkorolev): Do something smarter here, and wrap the whole thing into an IObservable<>. System.Threading.Thread.Sleep(50); } }
/// <summary> /// Retrieves any products that have a negative price in a DynamoDB table. /// </summary> /// <param name="productCatalogTable">A DynamoDB table object.</param> public static async Task FindProductsWithNegativePrice( Table productCatalogTable) { // Assume there is a price error. So we scan to find items priced < 0. var scanFilter = new ScanFilter(); scanFilter.AddCondition("Price", ScanOperator.LessThan, 0); Search search = productCatalogTable.Scan(scanFilter); do { var documentList = await search.GetNextSetAsync(); Console.WriteLine("\nFindProductsWithNegativePrice: printing ............"); foreach (var document in documentList) { PrintDocument(document); } }while (!search.IsDone); }
public async Task <List <Pet> > GetPets(int ownerId) { // Load our specific table var petTable = Table.LoadTable(DynamoClient, "Pets"); var scanFilter = new ScanFilter(); scanFilter.AddCondition("OwnerId", ScanOperator.Equal, ownerId); var search = petTable.Scan(scanFilter); //todo add pagination var documentList = new List <Document>(); do { documentList = await search.GetNextSetAsync(); } while (!search.IsDone); //Map results to response return(PetResponseBuilder.CreateList(documentList)); }
public async Task <List <Coupon> > GetCouponByStore(String storeName) { CreateTable(); ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("StoreName", ScanOperator.Equal, storeName); ScanOperationConfig soc = new ScanOperationConfig() { Filter = scanFilter }; DynamoDBContext context = new DynamoDBContext(dynamoDBClient); AsyncSearch <Coupon> search = context.FromScanAsync <Coupon>(soc, null); List <Coupon> documentList = new List <Coupon>(); do { documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken)); } while (!search.IsDone); return(documentList); }
public async Task <List <Book> > GetBooksAsync() { ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("Id", ScanOperator.NotEqual, 0); ScanOperationConfig soc = new ScanOperationConfig() { // AttributesToGet = new List { "Id", "Title", "ISBN", "Price" }, Filter = scanFilter }; DynamoDBContext context = new DynamoDBContext(dynamoDBClient); AsyncSearch <Book> search = context.FromScanAsync <Book>(soc, null); List <Book> documentList = new List <Book>(); do { documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken)); } while (!search.IsDone); return(documentList); }
public async Task <HttpResponse> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { var message = JsonConvert.DeserializeObject <TmpMessage>(input.Body); var table = Table.LoadTable(client, "ConnectionIds"); var scanFilter = new ScanFilter(); var search = table.Scan(scanFilter); var remaining = await search.GetRemainingAsync(); var httpClient = new HttpClient(); // Function no longer in use, therefore no up-to-date keys var signer = new AWS4RequestSigner("AccessKey", "SecretKey"); foreach (var doc in remaining) { var connectionId = doc["ConnectionId"]; var endpoint = $"https://{input.RequestContext.DomainName}/{input.RequestContext.Stage}/@connections/{connectionId}"; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(endpoint), Content = new StringContent(message.Message) }; request = await signer.Sign(request, "execute-api", "eu-west-1"); var response = await httpClient.SendAsync(request); Console.WriteLine(await response.Content.ReadAsStringAsync()); } return(new HttpResponse { statusCode = HttpStatusCode.OK }); }
//Scan the table public async Task <Data.data> Child() { var client = new AmazonDynamoDBClient(); Table reddit_til_table = Table.LoadTable(client, table); //Scan ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("id", ScanOperator.IsNotNull); ScanOperationConfig scanConfig = new ScanOperationConfig() { Filter = scanFilter, Select = SelectValues.SpecificAttributes, AttributesToGet = new List <string> { "id" } }; //Search Search tableSearch = reddit_til_table.Scan(scanConfig); //Loop of all documents - al items List <Document> all_TILs = new List <Document>(); do { all_TILs = await tableSearch.GetNextSetAsync(); foreach (var document in all_TILs) { ids.Add(document["id"].ToString()); } } while (!tableSearch.IsDone); //Return Document doc = await getChild(client, reddit_til_table); return(new Data().CastToData(doc)); }
private void SendMessageEventToAllConnectedClients(MessageEvent message) { var scanFilter = new ScanFilter(); var search = table.Scan(scanFilter); var getTask = search.GetRemainingAsync(); getTask.Wait(); var remaining = getTask.Result; var tasks = new List <Task>(); Console.WriteLine($"Connected ids: {remaining.Count}"); foreach (var doc in remaining) { var connectionId = doc["ConnectionId"]; Console.WriteLine($"Current id: {connectionId}"); var endpoint = $"https://{WEB_SOCKET_URL}/@connections/{connectionId}"; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(endpoint), Content = new StringContent(JsonConvert.SerializeObject(message)) }; // request.Headers.Add("Content-Type", "application/json"); Console.WriteLine($"Sign {connectionId}."); tasks.Add(signer.Sign(request, "execute-api", "eu-west-1") .ContinueWith(signedRequest => { Console.WriteLine($"Sending to {connectionId}."); httpClient.SendAsync(signedRequest.Result).Wait(); })); } Task.WaitAll(tasks.ToArray()); Console.WriteLine("Everything sent."); }
//public async void FindMedicineWithBarcode(long barcode, string table) //{ // GetItemOperationConfig config = new GetItemOperationConfig() // { // AttributesToGet = new List<string>() { "Barcode" }, // }; // // Primitive key = Medicine // Table tablename = Table.LoadTable(DynamoClient, table); // // tablename.GetItemAsync(Primitive Medicine.MedicineID, Primitive sortKey, GetItemOperationConfig config) // ScanFilter scanFilter = new ScanFilter(); // scanFilter.AddCondition("Barcode", ScanOperator.Equal, barcode); // ScanOperationConfig ScanConfig = new ScanOperationConfig() // { // AttributesToGet = new List<string> { "MedicineID", "Barcode" }, // Filter = scanFilter // }; // Search getMedicine = tablename.Scan(ScanConfig); // List<Document> result = await getMedicine.GetRemainingAsync(); // foreach (Document item in result) // { // foreach (string key in item.Keys) // { // DynamoDBEntry dbEntry = item[key]; // string val = dbEntry.ToString(); // if (key.ToLower() == "Barcode") // { // List<string> barcodes = dbEntry.AsListOfString(); // StringBuilder valueBuilder = new StringBuilder(); // foreach (string code in barcodes) // { // valueBuilder.Append(code).Append(", "); // } // val = valueBuilder.ToString(); // } // Console.WriteLine(string.Format("Property: {0}, value: {1}", key, val)); // } // } //} public async Task <string> FindPrescriptionForCurrentDate(string date) { ScanFilter filter = new ScanFilter(); ScanOperator op = ScanOperator.Equal; string attrName = "StartDate"; filter.AddCondition(attrName, op, date); Table tablename = Table.LoadTable(DynamoClient, "Prescription"); List <Document> prescriptions = await(tablename.Scan(filter)).GetRemainingAsync(); int newID = prescriptions.Count; string medicineName = ""; string numberOfTime = ""; string returnValue = ""; foreach (Document item in prescriptions) { foreach (string key in item.Keys) { if (key == "Barcode") { DynamoDBEntry dbEntry = item[key]; string val = dbEntry.ToString(); long barcodeValue = Convert.ToInt64(val); //find medicine name medicineName = await FindMedicineNameByBarcode(barcodeValue); } if (key == "NumberOfTime") { DynamoDBEntry dbEntry = item[key]; numberOfTime = dbEntry.ToString(); } returnValue = medicineName + " & " + numberOfTime; } } return(returnValue); }
public List <Artist> DbGetArtists(string a) { try { //Artist name to lower var artist = a.ToLower(); //Load artists table var table = Table.LoadTable(Client, "Artist"); //Filter for scan. Artist column matches artist input var filter = new ScanFilter(); filter.AddCondition("ArtistName", ScanOperator.Contains, artist); //Response var response = table.Scan(filter).GetNextSet(); //List to contain found artists var foundArtists = new List <Artist>(); //Loop through each item in the response and map it to a new Artist in the artist list foreach (var item in response) { foundArtists.Add(new Artist() { ArtistName = item["ArtistName"], ArtistId = int.Parse(item["ArtistID"]) }); } return(foundArtists); } catch (Exception ex) { MessageBox.Show(ex.Message); return(null); } }
private void FindRepliesWithNegativeVotes(Table productCatalogTable) { this.displayMessage += "\n***FindRepliesWithNegativeVotes***\n"; if (replyTable == null) { this.displayMessage += "\nLoad table before running scans"; return; } ThreadPool.QueueUserWorkItem((s) => { try { this.displayMessage += "\nRunning on background thread"; ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("Votes", ScanOperator.LessThan, 0); Search search = productCatalogTable.Scan(scanFilter); List <Document> documentList = new List <Document>(); do { documentList = search.GetNextSet(); Console.WriteLine("\nFindRepliesWithNegativeVotes: printing ............"); foreach (var document in documentList) { PrintDocument(document); } } while (!search.IsDone); this.displayMessage += "\nCompleted !\n"; } catch (Exception ex) { this.displayMessage += "\nFindRepliesWithNegativeVotes:" + ex.Message; Debug.LogException(ex); } }); }
public async Task <TKey[]> GetAggregateIdsAsync( CancellationToken cancellationToken = default) { var scanFilter = new ScanFilter(); //scanFilter.AddCondition("aggregateVersion", ScanOperator.Equal, 1); Search search = _table.Scan(scanFilter); var ids = new HashSet <TKey>(); do { List <Document> documents = await search.GetNextSetAsync(cancellationToken).ConfigureAwait(false); foreach (Document document in documents) { DynamoDBEntry entry = document["aggregateId"]; TKey id = Defaults.Convert <TKey>(entry); ids.Add(id); } }while (!search.IsDone); return(ids.ToArray()); }
public async Task <int> CalculateTime(string practiceId) { var tableName = "Appointment"; var client = new AmazonDynamoDBClient(RegionEndpoint.USEast1); var appointmentTable = Table.LoadTable(client, tableName); var scanFilter = new ScanFilter(); scanFilter.AddCondition("IsServed", ScanOperator.Equal, "false"); scanFilter.AddCondition("PracticeId", ScanOperator.Equal, practiceId); var searchResult = appointmentTable.Scan(scanFilter); List <Document> documentList = new List <Document>(); do { var documents = await searchResult.GetNextSetAsync(); documentList.AddRange(documents); } while (!searchResult.IsDone); return(documentList.Count * 15); }
public async Task <IActionResult> GetAsync() { var credentials = new BasicAWSCredentials(AWSAccessKeyId, AWSSecretAccessKey); var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USWest2); ScanFilter scanFilter = new ScanFilter(); // scanFilter.AddCondition("FirstName", ScanOperator.Equal, "Luis"); ScanOperationConfig soc = new ScanOperationConfig() { // AttributesToGet = new List { "Id", "Title", "ISBN", "Price" }, Filter = scanFilter }; DynamoDBContext context = new DynamoDBContext(client); AsyncSearch <EmployeesPTU> search = context.FromScanAsync <EmployeesPTU>(soc, null); List <EmployeesPTU> documentList = new List <EmployeesPTU>(); do { documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken)); } while (!search.IsDone); return(Ok(documentList)); }
/// <summary> /// Prepares parameters for a scan operation from the list of conditions /// </summary> internal static ScanFilter GetScanFilterForTable(this TranslationResult translationResult, Table tableDefinition) { // the last thing to do is to make a full scan var scanFilter = new ScanFilter(); //TODO: check for BETWEEN operator foreach (var condition in translationResult.Conditions.Flatten()) { if ( (condition.Item2.Values.Length == 1) && (condition.Item2.Values[0] == null) ) { switch (condition.Item2.Operator) { case ScanOperator.Equal: scanFilter.AddCondition(condition.Item1, ScanOperator.IsNull); break; case ScanOperator.NotEqual: scanFilter.AddCondition(condition.Item1, ScanOperator.IsNotNull); break; default: throw new InvalidOperationException(string.Format("You cannot use {0} operator with null value", condition.Item2.Operator)); } } else { scanFilter.AddCondition(condition.Item1, condition.Item2.Operator, condition.Item2.Values); } } return(scanFilter); }
private static void FindProductsWithNegativePriceWithConfig(Table productCatalogTable) { // Assume there is a price error. So we scan to find items priced < 0. ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("Price", ScanOperator.LessThan, 0); ScanOperationConfig config = new ScanOperationConfig() { Filter = scanFilter, Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "Title", "Id" } }; Search search = productCatalogTable.Scan(config); List<Document> documentList = new List<Document>(); do { documentList = search.GetNextSet(); Console.WriteLine("\nFindProductsWithNegativePriceWithConfig: printing ............"); foreach (var document in documentList) PrintDocument(document); } while (!search.IsDone); }
public async Task <bool> isBookedAsync(string teacherEmail, string date_timeslot) { Appointment newAppointment = new Appointment(); Table ThreadTable = Table.LoadTable(client, "Appointment"); ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("teacherEmailID", ScanOperator.Equal, teacherEmail); scanFilter.AddCondition("appointmentDate_timeSlot", ScanOperator.Equal, date_timeslot); scanFilter.AddCondition("status", ScanOperator.Equal, "made"); Search search = ThreadTable.Scan(scanFilter); var documents = await search.GetRemainingAsync(); if (documents.Count == 0) { return(false); } else { return(true); } }
private void InitAndLoadUsers() { lock (NetDbLock) { //inits and loads the users from the database Users = new Dictionary<string, User>(); ScanFilter scanFilter = new ScanFilter(); ScanOperationConfig config = new ScanOperationConfig() { AttributesToGet = new List<string> { DatabaseConfigs.UsersKey }, Filter = scanFilter }; config.Select = SelectValues.SpecificAttributes; Search search = networkDb.GetUsersTable().Scan(config); if (search.Count > 0) { foreach (var item in search.GetNextSet()) { Users.Add(item[DatabaseConfigs.UsersKey], GetUserById(item[DatabaseConfigs.UsersKey])); } } } }
static void Main(string[] args) { // Get an AmazonDynamoDBClient for the local DynamoDB database AmazonDynamoDBClient client = GetLocalClient(); // Get a Table object for the table that you created in Step 1 Table table = GetTableObject(client, "Movies"); if (table == null) { PauseForDebugWindow(); return; } /*----------------------------------------------------------------------- * 4.2a: Call Table.Scan to return the movies released in the 1950's, * displaying title, year, lead actor and lead director. *-----------------------------------------------------------------------*/ ScanFilter filter = new ScanFilter(); filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 }); ScanOperationConfig config = new ScanOperationConfig { AttributesToGet = new List <string> { "year, title, info" }, Filter = filter }; Search search = table.Scan(filter); // Display the movie information returned by this query Console.WriteLine("\n\n Movies released in the 1950's (Document Model):" + "\n--------------------------------------------------"); List <Document> docList = new List <Document>(); Document infoDoc; string movieFormatString = " \"{0}\" ({1})-- lead actor: {2}, lead director: {3}"; do { try { docList = search.GetNextSet(); } catch (Exception ex) { Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message); break; } foreach (var doc in docList) { infoDoc = doc["info"].AsDocument(); Console.WriteLine(movieFormatString, doc["title"], doc["year"], infoDoc["actors"].AsArrayOfString()[0], infoDoc["directors"].AsArrayOfString()[0]); } } while (!search.IsDone); /*----------------------------------------------------------------------- * 4.2b: Call AmazonDynamoDBClient.Scan to return all movies released * in the 1960's, only downloading the title, year, lead * actor and lead director attributes. *-----------------------------------------------------------------------*/ ScanRequest sRequest = new ScanRequest { TableName = "Movies", ExpressionAttributeNames = new Dictionary <string, string> { { "#yr", "year" } }, ExpressionAttributeValues = new Dictionary <string, AttributeValue> { { ":y_a", new AttributeValue { N = "1960" } }, { ":y_z", new AttributeValue { N = "1969" } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors[0]" }; ScanResponse sResponse; try { sResponse = client.Scan(sRequest); } catch (Exception ex) { Console.WriteLine("\n Error: Low-level scan failed, because: " + ex.Message); PauseForDebugWindow(); return; } // Display the movie information returned by this scan Console.WriteLine("\n\n Movies released in the 1960's (low-level):" + "\n-------------------------------------------"); foreach (Dictionary <string, AttributeValue> item in sResponse.Items) { Dictionary <string, AttributeValue> info = item["info"].M; Console.WriteLine(movieFormatString, item["title"].S, item["year"].N, info["actors"].L[0].S, info["directors"].L[0].S); } }
public async Task <ResponseModel <List <UserServicesItem> > > GetAsync(SearchParam fipso, SecurityModel securityModel) { ResponseModel <List <UserServicesItem> > response = new ResponseModel <List <UserServicesItem> >(); try { PagingInfo paging = new PagingInfo(); paging.CurrentPage = fipso.CurrentPage; paging.PageSize = fipso.PageSize; paging.SortDirection = fipso.SortDirection; paging.SortExpression = fipso.SortExpression; ScanFilter filter = new ScanFilter(); switch (fipso.Status) { case "Rejected": filter.AddCondition("RequestStatus", ScanOperator.Equal, "Rejected"); break; case "Approved": filter.AddCondition("RequestStatus", ScanOperator.Equal, "Approved"); break; default: filter.AddCondition("RequestStatus", ScanOperator.Equal, "Requested"); break; } if (string.IsNullOrEmpty(fipso.SortExpression)) { fipso.SortExpression = "SubmittedOn"; } if (paging.SortDirection != string.Empty) { fipso.SortExpression = fipso.SortExpression + " " + paging.SortDirection; } int rows = 0; IEnumerable <UserServicesItem> requestedItem = await _dynamodbContext.GetAsync(filter); var filterData = new List <UserServicesItem>(); if (!string.IsNullOrEmpty(fipso.SearchText)) { filterData = requestedItem.Where(x => x.BookName.ToLower().Contains(fipso.SearchText.ToLower()) || x.BookAuthor.ToLower().Contains(fipso.SearchText) || x.UserName.ToLower().Contains(fipso.SearchText) ).ToList(); } else { filterData = requestedItem.ToList(); } var resultList = from p in filterData.AsQueryable() select p; rows = resultList.Count(); var requestedBookList = resultList.OrderBy(fipso.SortExpression).Skip((paging.CurrentPage - 1) * paging.PageSize).Take(paging.PageSize).ToList(); paging.TotalRows = rows; paging.TotalPages = Functions.CalculateTotalPages(rows, paging.PageSize); response.Entity = requestedBookList; response.TotalRows = paging.TotalRows; response.TotalPages = paging.TotalPages; response.Status = true; } catch (AmazonServiceException amazonEx) { response.Status = false; response.ReturnMessage.Add($"Amazon error in table operation! Error: {amazonEx.Message}"); } catch (System.Exception ex) { response.Status = false; response.ReturnMessage.Add(ex.Message); } return(response); }
public static void Main() { bool response; var step = 1; // 1. Create a DynamoDB client connected to a DynamoDB-Local instance Console.WriteLine(StepString, step, "Create a DynamoDB client connected to a DynamoDB-Local instance"); response = createClient(UseDynamoDbLocal); if (!response) { Console.WriteLine("Could not create client, bye."); return; } pause(); step++; // Check whether table exists. var tableExists = CheckingTableExistence_async(MoviesTableName); if (tableExists.Result) { Console.WriteLine(" -- Table already exists..."); if (DeleteExistingTable) { var deleteTable = DeletingTable_async(MoviesTableName); if (!deleteTable.Result) { Console.WriteLine("Could not delete existing table, bye."); return; } } else { return; } } // 2. Create a table for movie data asynchronously Console.WriteLine(StepString, step, "Create a table for movie data"); var createTable = CreateTable_async(MoviesTableName, MovieItemsAttributes, MoviesKeySchema, MoviesTableProvisionedThroughput); if (!createTable.Result) { Console.WriteLine("Could not create table, bye."); return; } try { MoviesTable = Table.LoadTable(DdbIntro.Client, MoviesTableName); MoviesTableDescription = GetTableDescription(MoviesTableName).Result; } catch (Exception ex) { Console.WriteLine( " Error: Could not access the new '{0}' table after creating it;\n" + " Reason: {1}.", MoviesTableName, ex.Message); return; } pause(); step++; // 3. Load movie data into the Movies table asynchronously if ((MoviesTableDescription != null) && (MoviesTableDescription.ItemCount == 0)) { Console.WriteLine(StepString, step, "Load movie data into the Movies table"); var loadData = LoadingData_async(MoviesTable, MovieDataPath); if (!loadData.Result) { Console.WriteLine("Could not load data into table."); return; } } pause(); step++; // 4. Add a new movie to the Movies table Document newItemDocument = new Document { ["year"] = year, ["title"] = title, ["info"] = Document.FromJson( "{\"plot\" : \"Nothing happens at all.\",\"rating\" : 0}") }; Console.WriteLine(StepString, step, "Add a new movie to the Movies table"); var writeNew = WritingNewMovie_async(newItemDocument); if (!writeNew.Result) { Console.WriteLine("Could not add movie to table, bye."); return; } pause(); step++; // 5. Read and display the new movie record that was just added Console.WriteLine(StepString, step, "Read the new movie record that was just added"); var movieRecord = ReadingMovie_async(year, title); pause(); if (movieRecord.Result.Count < 1) { Console.WriteLine("Could not retrieve info about new movie."); } else { Console.WriteLine("Here is the movie:"); showDocument(movieRecord.Result); } pause(); step++; // 6. Update the new movie record in various ways //------------------------------------------------- // 6a. Create an UpdateItemRequest to: // -- modify the plot and rating of the new movie, and // -- add a list of actors to it Console.WriteLine(StepString, step + "a", "Change the plot and rating for the new movie and add a list of actors"); UpdateItemRequest updateRequest = new UpdateItemRequest() { TableName = MoviesTableName, Key = new Dictionary <string, AttributeValue> { { PartitionKeyName, new AttributeValue { N = "2018" } }, { SortKeyName, new AttributeValue { S = "The Big New Movie" } } }, ExpressionAttributeValues = new Dictionary <string, AttributeValue> { { ":r", new AttributeValue { N = "5.5" } }, { ":p", new AttributeValue { S = "Everything happens all at once!" } }, { ":a", new AttributeValue { L = new List <AttributeValue> { new AttributeValue { S = "Larry" }, new AttributeValue { S = "Moe" }, new AttributeValue { S = "Curly" } } } } }, UpdateExpression = "SET info.rating = :r, info.plot = :p, info.actors = :a", ReturnValues = "NONE" }; var updateMovie = UpdatingMovie_async(updateRequest); if (!updateMovie.Result) { Console.WriteLine("Could not update movie, bye."); return; } pause(); // 6b Change the UpdateItemRequest so as to increment the rating of the // new movie, and then make the update request asynchronously. Console.WriteLine(StepString, step + "b", "Increment the new movie's rating atomically"); Console.WriteLine(" -- Incrementing the rating of the new movie by 1..."); updateRequest.ExpressionAttributeValues = new Dictionary <string, AttributeValue> { { ":inc", new AttributeValue { N = "1" } } }; updateRequest.UpdateExpression = "SET info.rating = info.rating + :inc"; updateMovie = UpdatingMovie_async(updateRequest); if (!updateMovie.Result) { Console.WriteLine("Could not update movie, bye."); return; } pause(); // 6c Change the UpdateItemRequest so as to increment the rating of the // new movie, and then make the update request asynchronously. Console.WriteLine(StepString, step + "c", "Now try the same increment again with a condition that fails... "); Console.WriteLine(" -- Now trying to increment the new movie's rating, but this time\n" + " ONLY ON THE CONDITION THAT the movie has more than 3 actors..."); updateRequest.ExpressionAttributeValues.Add(":n", new AttributeValue { N = "3" }); updateRequest.ConditionExpression = "size(info.actors) > :n"; updateMovie = UpdatingMovie_async(updateRequest); if (!updateMovie.Result) { Console.WriteLine("Could not update movie, as expected."); } pause(); step++; // 7. Try conditionally deleting the movie that we added // 7a. Try conditionally deleting the movie that we added Console.WriteLine(StepString, step + "a", "Try deleting the new movie record with a condition that fails"); Console.WriteLine(" -- Trying to delete the new movie,\n" + " -- but ONLY ON THE CONDITION THAT its rating is 5.0 or less..."); Expression condition = new Expression(); condition.ExpressionAttributeValues[":val"] = 5.0; condition.ExpressionStatement = "info.rating <= :val"; var deleteItem = DeletingItem_async(MoviesTable, 2018, "The Big New Movie", condition); if (!deleteItem.Result) { Console.WriteLine("Could not delete movie, as expected."); } pause(); // 7b. Now increase the cutoff to 7.0 and try to delete again... Console.WriteLine(StepString, step + "b", "Now increase the cutoff to 7.0 and try to delete the movie again..."); Console.WriteLine(" -- Now trying to delete the new movie again,\n" + " -- but this time on the condition that its rating is 7.0 or less..."); condition.ExpressionAttributeValues[":val"] = 7.0; deleteItem = DeletingItem_async(MoviesTable, 2018, "The Big New Movie", condition); if (!deleteItem.Result) { Console.WriteLine("Could not delete movie, bye."); return; } pause(); step++; // 8. Query the Movies table in 3 different ways Search search; // 8a. Just query on the year Console.WriteLine(StepString, step + "a", "Query the Movies table using a Search object for all movies from 1985"); Console.WriteLine(" -- First, create a Search object..."); try { search = MoviesTable.Query(1985, new Expression()); } catch (Exception ex) { Console.WriteLine(" ERROR: Failed to create the Search object because:\n " + ex.Message); return; } Console.WriteLine(" -- Successfully created the Search object,\n" + " so now we'll display the movies retrieved by the query:"); pause(); var searchResponse = SearchListing_async(search); if (searchResponse.Result.Count < 1) { Console.WriteLine("Did not get any search results, bye."); return; } foreach (var docs in searchResponse.Result) { foreach (var doc in docs) { showMovieDocShort(doc); } } // 8b. SearchListing_async Console.WriteLine(StepString, step + "b", "Query for 1992 movies with titles from B... to Hzz... using Table.Query"); Console.WriteLine(" -- Now setting up a QueryOperationConfig for the 'Search'..."); QueryOperationConfig config = new QueryOperationConfig(); config.Filter = new QueryFilter(); config.Filter.AddCondition("year", QueryOperator.Equal, new DynamoDBEntry[] { 1992 }); config.Filter.AddCondition("title", QueryOperator.Between, new DynamoDBEntry[] { "B", "Hzz" }); config.AttributesToGet = new List <string> { "year", "title", "info" }; config.Select = SelectValues.SpecificAttributes; Console.WriteLine(" -- Creating the Search object based on the QueryOperationConfig"); try { search = MoviesTable.Query(config); } catch (Exception ex) { Console.WriteLine(" ERROR: Failed to create the Search object because:\n " + ex.Message); return; } Console.WriteLine(" -- Successfully created the Search object,\n" + " so now we'll display the movies retrieved by the query:"); pause(); searchResponse = SearchListing_async(search); if (searchResponse.Result.Count < 1) { Console.WriteLine("Did not get any search results, bye."); return; } foreach (var docs in searchResponse.Result) { foreach (var doc in docs) { showMovieDocShort(doc); } } // 8c. Query using a QueryRequest Console.WriteLine(StepString, step + "c", "Query the Movies table for 1992 movies with titles from M... to Tzz..."); Console.WriteLine(" -- Next use a low-level query to retrieve a selection of movie attributes"); QueryRequest qRequest = new QueryRequest { TableName = "Movies", ExpressionAttributeNames = new Dictionary <string, string> { { "#yr", "year" } }, ExpressionAttributeValues = new Dictionary <string, AttributeValue> { { ":qYr", new AttributeValue { N = "1992" } }, { ":tSt", new AttributeValue { S = "M" } }, { ":tEn", new AttributeValue { S = "Tzz" } } }, KeyConditionExpression = "#yr = :qYr and title between :tSt and :tEn", ProjectionExpression = "#yr, title, info.actors[0], info.genres, info.running_time_secs" }; Console.WriteLine(" -- Using a QueryRequest to get the lead actor and genres of\n" + " 1992 movies with titles between 'M...' and 'Tzz...'."); var clientQuery = ClientQuerying_async(qRequest); if (clientQuery.Result.Count < 1) { Console.WriteLine("Could not query for movie, bye."); return; } Console.WriteLine(" Here are the movies retrieved:" + " --------------------------------------------------------------------------"); foreach (Dictionary <string, AttributeValue> item in clientQuery.Result.Items) { showMovieAttrsShort(item); } Console.WriteLine(" -- Retrieved {0} movies.", clientQuery.Result.Items.Count); pause(); step++; // 9. Try scanning the movies table to retrieve movies from several decades // 9a. Use Table.Scan with a Search object and a ScanFilter to retrieve movies from the 1950s Console.WriteLine(StepString, step + "a", "Scan the Movies table to retrieve all movies from the 1950's"); ScanFilter filter = new ScanFilter(); filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 }); ScanOperationConfig scanConfig = new ScanOperationConfig { Filter = filter }; Console.WriteLine(" -- Creating a Search object based on a ScanFilter"); try { search = MoviesTable.Scan(scanConfig); } catch (Exception ex) { Console.WriteLine(" ERROR: Failed to create the Search object because:\n " + ex.Message); return; } Console.WriteLine(" -- Successfully created the Search object"); pause(); searchResponse = SearchListing_async(search); if (searchResponse.Result.Count < 1) { Console.WriteLine("Did not get any search results, bye."); return; } foreach (var docs in searchResponse.Result) { foreach (var doc in docs) { showMovieDocShort(doc); } } // 9b. Use AmazonDynamoDBClient.Scan to retrieve movies from the 1960s Console.WriteLine(StepString, step + "b", "Use a low-level scan to retrieve all movies from the 1960's"); Console.WriteLine(" -- Using a ScanRequest to get movies from between 1960 and 1969"); ScanRequest sRequest = new ScanRequest { TableName = "Movies", ExpressionAttributeNames = new Dictionary <string, string> { { "#yr", "year" } }, ExpressionAttributeValues = new Dictionary <string, AttributeValue> { { ":y_a", new AttributeValue { N = "1960" } }, { ":y_z", new AttributeValue { N = "1969" } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs" }; var clientScan = ClientScanning_async(sRequest); Console.WriteLine(" Here are the movies retrieved:\n" + " --------------------------------------------------------------------------"); foreach (Dictionary <string, AttributeValue> item in clientScan.Result.Items) { showMovieAttrsShort(item); } Console.WriteLine(" -- Retrieved {0} movies.", clientScan.Result.Items.Count); pause(); step++; // 10. Finally, delete the Movies table and all its contents Console.WriteLine(StepString, step, "Finally, delete the Movies table and all its contents"); var deletingTable = DeletingTable_async(MoviesTableName); if (!deletingTable.Result) { Console.WriteLine("Could not delete the table."); } Console.WriteLine( "\n=================================================================================" + "\n This concludes the DynamoDB Getting-Started demo program" + "\n================================================================================="); pause(); }
private void TestHashTable(Table hashTable, DynamoDBEntryConversion conversion) { // Put an item Document doc = new Document(); doc["Id"] = 1; doc["Product"] = "CloudSpotter"; doc["Company"] = "CloudsAreGrate"; doc["IsPublic"] = true; doc["Price"] = 1200; doc["Tags"] = new HashSet <string> { "Prod", "1.0" }; doc["Aliases"] = new List <string> { "CS", "Magic" }; doc["Developers"] = new List <Document> { new Document(new Dictionary <string, DynamoDBEntry> { { "Name", "Alan" }, { "Age", 29 } }), new Document(new Dictionary <string, DynamoDBEntry> { { "Name", "Franco" }, { "Age", 32 } }) }; doc["Garbage"] = "asdf"; Assert.AreEqual("asdf", doc["Garbage"].AsString()); hashTable.PutItem(doc); // Get the item by hash key Document retrieved = hashTable.GetItem(1); Assert.IsFalse(AreValuesEqual(doc, retrieved)); var convertedDoc = doc.ForceConversion(conversion); Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved)); // Get the item by document retrieved = hashTable.GetItem(doc); // Verify retrieved document Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved, conversion)); var tagsRetrieved = retrieved["Tags"]; Assert.IsTrue(tagsRetrieved is PrimitiveList); Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count); // Test bool storage for different conversions var isPublicRetrieved = retrieved["IsPublic"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual("1", isPublicRetrieved.AsPrimitive().Value as string); } else { Assert.IsTrue(isPublicRetrieved is DynamoDBBool); } // Test HashSet<string> storage for different conversions var aliasesRetrieved = retrieved["Aliases"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual(2, aliasesRetrieved.AsPrimitiveList().Entries.Count); } else { Assert.AreEqual(2, aliasesRetrieved.AsDynamoDBList().Entries.Count); } List <Document> developers = retrieved["Developers"].AsListOfDocument(); Assert.AreEqual(2, developers.Count); AssertExtensions.ExpectException(() => aliasesRetrieved.AsListOfDocument(), typeof(InvalidCastException)); // Update the item doc["Tags"] = new List <string> { "Prod", "1.0", "2.0" }; doc["Developers"] = new DynamoDBList(new List <DynamoDBEntry> { new Document(new Dictionary <string, DynamoDBEntry> { { "Name", "Alan" }, { "Age", 29 } }) }); // Delete the Garbage attribute doc["Garbage"] = null; Assert.IsNull(doc["Garbage"].AsString()); hashTable.UpdateItem(doc); retrieved = hashTable.GetItem(1); Assert.IsFalse(AreValuesEqual(doc, retrieved, conversion)); doc.Remove("Garbage"); Assert.IsTrue(AreValuesEqual(doc, retrieved, conversion)); developers = retrieved["Developers"].AsListOfDocument(); Assert.AreEqual(1, developers.Count); // Create new, circularly-referencing item Document doc2 = doc.ForceConversion(conversion); doc2["Id"] = doc2["Id"].AsInt() + 1; doc2["Price"] = 94; doc2["Tags"] = null; doc2["IsPublic"] = false; doc2["Parent"] = doc2; AssertExtensions.ExpectException(() => hashTable.UpdateItem(doc2)); // Remove circular reference and save new item doc2.Remove("Parent"); hashTable.UpdateItem(doc2); // Scan the hash-key table var items = hashTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(2, items.Count); // Scan by pages var search = hashTable.Scan(new ScanOperationConfig { Limit = 1 }); items.Clear(); while (!search.IsDone) { var set = search.GetNextSet(); items.AddRange(set); } Assert.AreEqual(2, items.Count); // Query against GlobalIndex var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "CloudsAreGrate"); queryFilter.AddCondition("Price", QueryOperator.GreaterThan, 100); search = hashTable.Query(new QueryOperationConfig { IndexName = "GlobalIndex", Filter = queryFilter }); items = search.GetRemaining(); Assert.AreEqual(1, items.Count); // Scan for specific tag var scanFilter = new ScanFilter(); scanFilter.AddCondition("Tags", ScanOperator.Contains, "2.0"); search = hashTable.Scan(scanFilter); items = search.GetRemaining(); Assert.AreEqual(1, items.Count); // Delete the item by hash key hashTable.DeleteItem(1); Assert.IsNull(hashTable.GetItem(1)); // Delete the item by document hashTable.DeleteItem(doc2); Assert.IsNull(hashTable.GetItem(doc2)); // Scan the hash-key table to confirm it is empty items = hashTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(0, items.Count); // Batch-put items var batchWrite = hashTable.CreateBatchWrite(); batchWrite.AddDocumentToPut(doc); batchWrite.AddDocumentToPut(doc2); batchWrite.Execute(); // Batch-get items var batchGet = hashTable.CreateBatchGet(); batchGet.AddKey(1); batchGet.AddKey(doc2); batchGet.Execute(); Assert.AreEqual(2, batchGet.Results.Count); // Batch-delete items batchWrite = hashTable.CreateBatchWrite(); batchWrite.AddItemToDelete(doc); batchWrite.AddKeyToDelete(2); batchWrite.Execute(); // Batch-get non-existent items batchGet = hashTable.CreateBatchGet(); batchGet.AddKey(1); batchGet.AddKey(doc2); batchGet.Execute(); Assert.AreEqual(0, batchGet.Results.Count); // Scan the hash-key table to confirm it is empty items = hashTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(0, items.Count); }
private void TestHashRangeTable(Table hashRangeTable, DynamoDBEntryConversion conversion) { // Put an item Document doc1 = new Document(); doc1["Name"] = "Alan"; doc1["Age"] = 31; doc1["Company"] = "Big River"; doc1["Score"] = 120; doc1["IsTester"] = true; doc1["Manager"] = "Barbara"; doc1["Aliases"] = new HashSet <string> { "Al", "Steve" }; doc1["PastManagers"] = new List <string> { "Carl", "Karl" }; hashRangeTable.PutItem(doc1); // Update a non-existent item creates the item Document doc2 = new Document(); doc2["Name"] = "Chuck"; doc2["Age"] = 30; doc2["Company"] = "Big River"; doc2["Score"] = 94; doc1["IsTester"] = false; doc2["Manager"] = "Barbara"; doc2["Aliases"] = new HashSet <string> { "Charles" }; hashRangeTable.UpdateItem(doc2); // Save more items Document doc3 = new Document(); doc3["Name"] = "Diane"; doc3["Age"] = 40; doc3["Company"] = "Madeira"; doc1["IsTester"] = true; doc3["Score"] = 140; doc3["Manager"] = "Eva"; hashRangeTable.UpdateItem(doc3); var oldDoc3 = doc3.Clone() as Document; // Changing the range key will force a creation of a new item doc3["Age"] = 24; doc3["Score"] = 101; hashRangeTable.UpdateItem(doc3); // Get item var retrieved = hashRangeTable.GetItem("Alan", 31); // Verify retrieved document Assert.IsTrue(AreValuesEqual(doc1, retrieved, conversion)); var tagsRetrieved = retrieved["Aliases"]; Assert.IsTrue(tagsRetrieved is PrimitiveList); Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count); // Test bool storage for different conversions var isTesterRetrieved = retrieved["IsTester"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual("1", isTesterRetrieved.AsPrimitive().Value as string); } else { Assert.IsTrue(isTesterRetrieved is DynamoDBBool); } // Test HashSet<string> storage for different conversions var pastManagersRetrieved = retrieved["PastManagers"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual(2, pastManagersRetrieved.AsPrimitiveList().Entries.Count); } else { Assert.AreEqual(2, pastManagersRetrieved.AsDynamoDBList().Entries.Count); } // Get item using GetItem overloads that expect a key in different ways retrieved = hashRangeTable.GetItem(doc2); Assert.IsTrue(AreValuesEqual(doc2, retrieved, conversion)); retrieved = hashRangeTable.GetItem(oldDoc3, new GetItemOperationConfig { ConsistentRead = true }); Assert.IsTrue(AreValuesEqual(oldDoc3, retrieved, conversion)); retrieved = hashRangeTable.GetItem("Diane", 24, new GetItemOperationConfig { ConsistentRead = true }); Assert.IsTrue(AreValuesEqual(doc3, retrieved, conversion)); // Scan the hash-and-range-key table var items = hashRangeTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(4, items.Count); // Scan by pages var search = hashRangeTable.Scan(new ScanOperationConfig { Limit = 1 }); items.Clear(); while (!search.IsDone) { var set = search.GetNextSet(); items.AddRange(set); } Assert.AreEqual(4, items.Count); // Scan in parallel var segment1 = hashRangeTable.Scan(new ScanOperationConfig { Segment = 0, TotalSegments = 2 }).GetRemaining(); var segment2 = hashRangeTable.Scan(new ScanOperationConfig { Segment = 1, TotalSegments = 2 }).GetRemaining(); Assert.AreEqual(4, segment1.Count + segment2.Count); // Query items items = hashRangeTable.Query("Diane", new QueryFilter()).GetRemaining(); Assert.AreEqual(2, items.Count); // Query local index items = hashRangeTable.Query(new QueryOperationConfig { IndexName = "LocalIndex", Filter = new QueryFilter("Name", QueryOperator.Equal, "Diane") }).GetRemaining(); Assert.AreEqual(2, items.Count); // Query global index var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "Big River"); queryFilter.AddCondition("Score", QueryOperator.GreaterThan, 100); items = hashRangeTable.Query(new QueryOperationConfig { IndexName = "GlobalIndex", Filter = queryFilter }).GetRemaining(); Assert.AreEqual(1, items.Count); // Scan local index var scanFilter = new ScanFilter(); scanFilter.AddCondition("Name", ScanOperator.Equal, "Diane"); items = hashRangeTable.Scan(new ScanOperationConfig { IndexName = "LocalIndex", Filter = scanFilter }).GetRemaining(); Assert.AreEqual(2, items.Count); // Scan global index scanFilter = new ScanFilter(); scanFilter.AddCondition("Company", ScanOperator.Equal, "Big River"); scanFilter.AddCondition("Score", ScanOperator.GreaterThan, 100); items = hashRangeTable.Query(new QueryOperationConfig { IndexName = "GlobalIndex", Filter = queryFilter }).GetRemaining(); Assert.AreEqual(1, items.Count); }
/// <summary> /// A utility method for cleaning up expired sessions that IIS failed to delete. The method performs a scan on the table /// with a condition that the expiration date is in the past and calls delete on all the keys returned. Scans can be costly on performance /// so use this method sparingly like a nightly or weekly clean job. /// </summary> /// <param name="dbClient">The AmazonDynamoDB client used to find a delete expired sessions.</param> /// <param name="tableName">The table to search.</param> public static void DeleteExpiredSessions(AmazonDynamoDB dbClient, string tableName) { Table table = Table.LoadTable(dbClient, tableName, Table.DynamoDBConsumer.SessionStateProvider); ScanFilter filter = new ScanFilter(); filter.AddCondition(ATTRIBUTE_EXPIRES, ScanOperator.LessThan, DateTime.Now); ScanOperationConfig config = new ScanOperationConfig(); config.AttributesToGet = new List<string>(); config.AttributesToGet.Add(ATTRIBUTE_SESSION_ID); config.Filter = filter; Search search = table.Scan(config); do { List<Document> page = search.GetNextSet(); foreach (var document in page) { table.DeleteItem(document); } } while (!search.IsDone); }
public async Task <ResponseModel <IdentityViewModel> > Register(UserSignUpModel model) { ResponseModel <IdentityViewModel> response = new ResponseModel <IdentityViewModel>(); try { ScanFilter filter = new ScanFilter(); filter.AddCondition("Email", ScanOperator.Equal, model.Email); filter.AddCondition("IsDeleted", ScanOperator.Equal, false); IEnumerable <UserDetails> UserList = await _context.GetAsync(filter); if (!UserList.Any()) { model.Password = CommonHelper.CreatePassword(8); UserDetails userModel = _mapper.Map <UserDetails>(model); userModel.AddedOn = DateTime.UtcNow; userModel.Salt = Hasher.GetSalt(); userModel.Password = Hasher.GenerateHash(userModel.Password + userModel.Salt); userModel.UserName = model.Email; userModel.Email = model.Email; userModel.Id = Guid.NewGuid().ToString(); //Need to pull dynamicly from db Roles userRole = new Roles(); userRole.Description = ""; userRole.Id = Guid.NewGuid().ToString(); userRole.RomeName = StaticRoles.Student; userModel.Usertype = userRole.RomeName; userModel.Roles = userRole; userModel.IsActive = true; userModel.IsDeleted = false; userModel.IsStatic = false; await this._context.SaveAsync(userModel); response.Entity = _mapper.Map <IdentityViewModel>(userModel); response.ReturnMessage.Add("User has been Added successfully."); response.Status = true; // Sending User Registration Edm // MailHelper _mailServices = new MailHelper(); //tem fixes StringBuilder sb = new StringBuilder(); sb.Append("UserName :"******"password :"******"", userModel.Email, "Welcome", sb.ToString(), "", ""); await _mailService.SendMail("", userModel.Email, "Welcome to inventory management system", sb.ToString()); } else { response.Entity = new IdentityViewModel(); response.ReturnMessage.Add("User already exist."); response.Status = true; } } catch (Exception ex) { response.Status = false; response.ReturnMessage.Add(ex.Message); } return(response); }
string BuildSnsTopicString(TimeSpan timeTaken) { AWSXRayRecorder.Instance.BeginSubsegment("Build SNS Topic String"); StringBuilder sbText = new StringBuilder(); var strDDBTableName = System.Environment.GetEnvironmentVariable("BatTable"); Table usageTypeTable = Table.LoadTable(dynamoDBClient.Value, strDDBTableName); ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("Processed", ScanOperator.Equal, DynamoDBBool.True); scanFilter.AddCondition("Triggered", ScanOperator.Equal, DynamoDBBool.True); Search search = usageTypeTable.Scan(scanFilter); List <Document> documentList = new List <Document>(); do { documentList = search.GetRemainingAsync().GetAwaiter().GetResult(); if (documentList.Count > 0 && sbText.Length == 0) { sbText.AppendLine("Billing Anomaly Tracker" + Environment.NewLine); } foreach (var document in documentList) { var usageType = document["id"].AsString(); var averageDaily = document["AverageDaily"].AsDouble(); var previousDay = document["PreviousDay"].AsDouble(); var increaseBy = document["IncreaseBy"].AsDouble(); var strYesterdayDate = document["YesterdayDate"].AsString(); var dtYesterdayDate = DateTime.ParseExact(strYesterdayDate, "yyyy-MM-dd", CultureInfo.InvariantCulture); sbText.AppendLine($"{usageType} - increase by {increaseBy.ToString("P")} - Cost for {dtYesterdayDate.ToString("d MMM yyyy")}: {previousDay.ToString("C")} - Average Daily Cost: {averageDaily.ToString("C")}"); foreach (var attribute in document.GetAttributeNames()) { string stringValue = null; var value = document[attribute]; if (value is Primitive) { stringValue = value.AsPrimitive().Value.ToString(); } else if (value is PrimitiveList) { stringValue = string.Join(",", (from primitive in value.AsPrimitiveList().Entries select primitive.Value).ToArray()); } LambdaLogger.Log($"{attribute} - {stringValue}"); } } } while (!search.IsDone); if (sbText.Length > 0) { sbText.AppendLine($"Time taken for processing: {timeTaken.ToString(@"d\.hh\:mm\:ss")}"); } AWSXRayRecorder.Instance.EndSubsegment(); return(sbText.ToString()); }
public async Task <List <Product> > FindAsync(ProductFilterRequest filters, CancellationToken cancellationToken) { var includedInactive = filters.IncludedInactive ? "" : Status.Active.ToString(); // Create a filter base a scan condition var opConfig = new DynamoDBOperationConfig { QueryFilter = new List <ScanCondition>() }; if (!string.IsNullOrWhiteSpace(filters.Description)) { opConfig.QueryFilter.Add(new ScanCondition(nameof(Product.Description), ScanOperator.Contains, filters.Description)); } if (filters.ProductType != ProductType.None) { opConfig.QueryFilter.Add(new ScanCondition(nameof(Product.ProductType), ScanOperator.Contains, filters.ProductType)); } if (!filters.IncludedInactive) { opConfig.QueryFilter.Add(new ScanCondition(nameof(Product.Status), ScanOperator.Equal, Status.Active)); } var sortKey = new List <string>(); if (filters.ValidityStart.HasValue) { sortKey.Add(filters.ValidityStart.Value.ToShortDateString()); } if (filters.ValidityEnd.HasValue) { sortKey.Add(filters.ValidityEnd.Value.ToShortDateString()); } // When partition key exists ! if (!string.IsNullOrWhiteSpace(filters.Manufacturer)) { // query filters use in a filter by composite key var queryFilter = new QueryFilter(); queryFilter.AddCondition(nameof(Product.PartitionKey), QueryOperator.Equal, filters.Manufacturer); if (sortKey.Any()) { queryFilter.AddCondition(nameof(Product.SortKey), QueryOperator.BeginsWith, string.Join("#", sortKey)); } // Use scan condition and query filter (filter by primary key) return(await Context.FromQueryAsync <Product>(new QueryOperationConfig { Filter = queryFilter, Limit = filters.Take }, opConfig).GetRemainingAsync(cancellationToken)); } // Table scan !! scan condition shouldn't contain a primary key var scanFilter = new ScanFilter(); scanFilter.AddCondition(nameof(Product.SortKey), ScanOperator.BeginsWith, string.Join("#", sortKey)); return(await Context.FromScanAsync <Product>(new ScanOperationConfig { Limit = 10 }, opConfig).GetRemainingAsync(cancellationToken)); }
public static void RunDocumentModelSample() { Console.WriteLine("Loading Businesses table"); Table table = Table.LoadTable(client, "Businesses"); Console.WriteLine("Creating and saving first item"); Document chainStore2 = new Document(); chainStore2["Name"] = "Big Sales Inc"; chainStore2["Id"] = 2; chainStore2["Owner"] = "Big Sales Corp"; chainStore2["Managers"] = new List <string> { "Samantha Jones", "Richard Frost" }; chainStore2["FoundedDate"] = new DateTime(1980, 7, 4); chainStore2["Address"] = "123 Main Street, New York, New York"; chainStore2["Employees"] = 46; chainStore2["State"] = "NY"; table.PutItem(chainStore2); Console.WriteLine("Creating and saving first item"); Document chainStore13 = new Document(); chainStore13["Name"] = "Big Sales Inc"; chainStore13["Id"] = 13; chainStore13["Owner"] = "Big Sales Corp"; chainStore13["Managers"] = new List <string> { "Anil Garg", "Alex Short" }; chainStore13["FoundedDate"] = new DateTime(1999, 3, 15); chainStore13["Address"] = "1999 West Ave, Chicago, Illinois"; chainStore13["Employees"] = 54; chainStore13["State"] = "IL"; table.PutItem(chainStore13); Console.WriteLine("Creating and saving second item"); Document tinyDiner = new Document(); tinyDiner["Name"] = "Tiny Map-themed Diner"; tinyDiner["Id"] = 0; tinyDiner["Owner"] = "John Doe"; tinyDiner["FoundedDate"] = new DateTime(1974, 12, 10); tinyDiner["Address"] = "800 Lincoln Ave, Seattle, Washington"; tinyDiner["State"] = "WA"; table.PutItem(tinyDiner); Console.WriteLine("Creating and saving third item"); Document internetStore = new Document(); internetStore["Name"] = "Best Online Store Ever"; internetStore["Id"] = 0; internetStore["Owner"] = "Jane Doe"; internetStore["FoundedDate"] = new DateTime(1994, 2, 19); internetStore["Employees"] = 5; internetStore["Url"] = "http://www.best-online-store-ever.fake"; internetStore["Phone"] = "425-555-1234"; table.PutItem(internetStore); Console.WriteLine("Loading item"); Document doc1 = table.GetItem("Big Sales Inc", 2); Console.WriteLine("Attribute counts match (should be true): " + (chainStore2.GetAttributeNames().Count == doc1.GetAttributeNames().Count)); Console.WriteLine("Loading item..."); Document doc2 = table.GetItem("Best Online Store Ever", 0); Console.WriteLine("Attribute counts match (should be true): " + (chainStore2.GetAttributeNames().Count == doc1.GetAttributeNames().Count)); Console.WriteLine("Change item: remove one attribute, add one, modify one attribute"); doc2["Phone"] = null; doc2["Twitter"] = "best-online-store-ever"; doc2["Employees"] = 4; Console.WriteLine("Updating item"); table.UpdateItem(doc2); Console.WriteLine("Reloading item"); doc2 = table.GetItem("Best Online Store Ever", 0); Console.WriteLine("Phone attribute present (should be false): " + doc2.Contains("Phone")); Console.WriteLine("Twitter attribute present (should be true): " + doc2.Contains("Twitter")); Console.WriteLine("Employees attribute equals 4: " + (object.Equals(doc2["Employees"].AsPrimitive().Value, "4"))); Console.WriteLine("Loading nonexistent item"); Document doc3 = table.GetItem("Big Sales Inc", 3); Console.WriteLine("Returned document == null (should be true): " + (doc3 == null)); Search query; Console.WriteLine(); Console.WriteLine("Querying for items (Equals)"); query = table.Query("Big Sales Inc", new QueryFilter("Id", QueryOperator.Equal, 2)); List <Document> queryItems1 = query.GetRemaining(); Console.WriteLine("Number of items returned (should be 1): " + queryItems1.Count); Console.WriteLine(); Console.WriteLine("Querying for items (Between)"); QueryFilter filter = new QueryFilter(); filter.AddCondition("Name", QueryOperator.Equal, "Big Sales Inc"); filter.AddCondition("Id", QueryOperator.Between, 0, 15); QueryOperationConfig queryConfig = new QueryOperationConfig { Filter = filter, Limit = 1 }; query = table.Query(queryConfig); int totalItems = 0; while (!query.IsDone) { Console.WriteLine("Retrieving next set (page) of items"); List <Document> querySet = query.GetNextSet(); Console.WriteLine("Number of items returned in set (should be 1, unless last set, which will be 0): " + querySet.Count); foreach (Document doc in querySet) { Console.WriteLine("Retrieving individual properties"); Primitive name = doc["Name"].AsPrimitive(); Primitive id = doc["Id"].AsPrimitive(); PrimitiveList managers = doc["Managers"].AsPrimitiveList(); Console.WriteLine("Name = {0}, Id = {1}, # of managers = {2}", name.Value, id.Value, managers.Entries.Count); totalItems++; } } Console.WriteLine("Total items found (should be 2): " + totalItems); Search scan; ScanFilter scanFilter; Console.WriteLine(); Console.WriteLine("Scanning for items (GreaterThan)"); scanFilter = new ScanFilter(); scanFilter.AddCondition("Employees", ScanOperator.GreaterThan, 50); scan = table.Scan(scanFilter); List <Document> scanItems1 = scan.GetRemaining(); Console.WriteLine("Number of items returned (should be 1): " + scanItems1.Count); Console.WriteLine(); Console.WriteLine("Scanning for items (GreaterThan and LessThan)"); scanFilter = new ScanFilter(); scanFilter.AddCondition("Employees", ScanOperator.GreaterThan, 2); scanFilter.AddCondition("FoundedDate", ScanOperator.LessThan, new DateTime(1993, 1, 1)); scan = table.Scan(scanFilter); List <Document> scanItems2 = scan.GetRemaining(); Console.WriteLine("Number of items returned (should be 1): " + scanItems2.Count); Console.WriteLine(); Console.WriteLine("Retrieving an item"); Document existingDoc = table.GetItem("Big Sales Inc", 13); Console.WriteLine("Returned document == null (should be false): " + (existingDoc == null)); Console.WriteLine("Deleting item"); table.DeleteItem("Big Sales Inc", 13); Console.WriteLine("Retrieving same item"); existingDoc = table.GetItem("Big Sales Inc", 13); Console.WriteLine("Returned document == null (should be true): " + (existingDoc == null)); Console.WriteLine(); Console.WriteLine("Scanning for items (no filter) and deleting all"); scanFilter = new ScanFilter(); scan = table.Scan(scanFilter); List <Document> scanItems3 = scan.GetRemaining(); Console.WriteLine("Number of items returned (should be 3): " + scanItems3.Count); for (int i = 0; i < scanItems3.Count; i++) { Document item = scanItems3[i]; Console.WriteLine("Deleting item {0} of {1}", i + 1, scanItems3.Count); table.DeleteItem(item); } Console.WriteLine("Scanning table again"); scan = table.Scan(scanFilter); scanItems3 = scan.GetRemaining(); Console.WriteLine("Number of items returned (should be 0): " + scanItems3.Count); }
public async Task <IActionResult> getbook([FromHeader] string Authorization, [FromBody] OrderBook book) { try { long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient(); Table UserTable = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry"); Document searchdetails = new Document(); try { string[] autharray = Authorization.Split(' '); string authtype = autharray[0]; string authstring = autharray[1]; if (authtype == "Basic") { byte[] data = Convert.FromBase64String(authstring); string decodedString = Encoding.UTF8.GetString(data); string[] splitauth = decodedString.Split(":"); string id = splitauth[0]; string secret = splitauth[1]; Console.WriteLine(id + secret); ScanOperationConfig scanOperation = new ScanOperationConfig(); ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id); Search search = UserTable.Scan(scanOperation); List <Document> details = await search.GetRemainingAsync(); foreach (Document doc in details) { if (!string.IsNullOrWhiteSpace(doc["DefaultId"])) { if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id) { Console.WriteLine("successful auth"); searchdetails = doc; break; } } else { continue; } return(BadRequest("Id not found")); } } else { return(BadRequest("Bad authorization")); } } catch { return(BadRequest("authorizaion failed")); } Table orderbooktable; if (book.symbol == "SPYUSD") { orderbooktable = Table.LoadTable(amazonDynamoDBClient, "OrderBook"); } else { return(BadRequest("bad symbol")); } ScanOperationConfig config = new ScanOperationConfig(); ScanFilter filter = new ScanFilter(); filter.AddCondition("Price", ScanOperator.IsNotNull); config.Filter = filter; config.AttributesToGet.Add("Price"); config.AttributesToGet.Add("Volume"); config.AttributesToGet.Add("Type"); Search searchs = orderbooktable.Scan(config); List <Document> orderbook = await searchs.GetRemainingAsync(); List <ReturnOrderBook> rob = new List <ReturnOrderBook>(); foreach (Document d in orderbook) { rob.Add(new ReturnOrderBook() { Price = d["Price"].ToString(), Volume = d["Volume"].ToString(), Type = d["Type"].ToString() }); } string json = JsonConvert.SerializeObject(rob); return(Content(json, "application/json")); } catch { return(BadRequest("something went wrong")); } }