/// <summary> /// PollyNotes-SearchFunction /// /// This lambda function is integrated with the following API methods: /// /notes/search/GET /// /// This function does the following: /// /// 1. Takes a JSON payload from API gateway and converts it into a Note POCO <see cref="Note"/> /// 2. Queries DynamoDB using the QueryAsync feature. It will use the userId for the Partition Key, but a Filter will need /// to be applied to do the search based on the note text. /// 3. Returns the List of Note found /// </summary> /// <param name="note">POCO of Note from the JSON payload from API GW to Lambda. Only userId and note will be set.</param> /// <param name="context">Lambda context</param> /// <returns>List of Note from the Query to DynamoDB based on the userId and the note</returns> public List <Note> FunctionHandler(Note note, ILambdaContext context) { // The note object contains the userId and a partial note sent from API GW in the /notes/search/GET // { // "userId": "...", // "note": "..." // } Console.WriteLine("Initiating PollyNotes-SearchFunction..."); Console.WriteLine("Note received: " + JsonConvert.SerializeObject(note)); // Create the DynamoDB client and the Context for Object Persistence Model AmazonDynamoDBClient client = new AmazonDynamoDBClient(); DynamoDBContext ddbcontext = new DynamoDBContext(client); // Create a DynamoDB Operation Config to pass in a QueryFilter on the note // Since the note attribute isn't a key, we need to use a QueryFilter // The QueryFilter takes a list of ScanCondition DynamoDBOperationConfig opConfig = new DynamoDBOperationConfig() { QueryFilter = new List <ScanCondition>() { new ScanCondition("note", ScanOperator.Contains, note.note) } }; // Use the QueryAsync method to issue a query to DynamoDB based on the userId and QueryFilter // We are using an Async command due to the .netcore SDK which doesn't support sync invokes // We are using the Note POCO defined with the Object Persistence Model so all the data // will be mapped to the right entries. The Table name is also defined in the POCO AsyncSearch <Note> noteQuery = ddbcontext.QueryAsync <Note>(note.userId, opConfig); // Retrieve all of the notes based on the Query from DynamoDB and wait Task <List <Note> > searchTask = noteQuery.GetRemainingAsync(); searchTask.Wait(); // Once the list of Note has been fetched entirely, check for Exceptions. // If there are no Exceptions if (searchTask.Exception == null) { Console.WriteLine("Successfully executed QueryAsync with userId: " + note.userId + " and text containing: " + note.note); // Log the Notes found Console.WriteLine("Notes found in DynamoDB: " + JsonConvert.SerializeObject(searchTask.Result)); // Return the list return(searchTask.Result); } else { // There was an exception, log the entry data and the exception Console.WriteLine("Unable to QueryAsync with userId: " + note.userId + " and text containing: " + note.note); Console.WriteLine(searchTask.Exception); // Return an empty list return(new List <Note>()); } }
public async Task <IEnumerable <BetsStat> > GetBetsStats() { AsyncSearch <BetsStat> search = context.ScanAsync <BetsStat>(Enumerable.Empty <ScanCondition>(), null); List <BetsStat> result = await search.GetRemainingAsync(); return(result); }
/// <summary> /// Queries a DynamoDB table to find replies posted within the last 15 days. /// </summary> /// <param name="context">The DynamoDB context used to perform the query.</param> /// <param name="forumName">The name of the forum we're interested in.</param> /// <param name="threadSubject">The thread object containing the query parameters.</param> public static async Task FindRepliesInLast15Days( IDynamoDBContext context, string forumName, string threadSubject) { string replyId = $"{forumName} #{threadSubject}"; DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15); List <object> times = new List <object>(); times.Add(twoWeeksAgoDate); List <ScanCondition> scs = new List <ScanCondition>(); var sc = new ScanCondition("LastPostedBy", ScanOperator.GreaterThan, times.ToArray()); scs.Add(sc); var cfg = new DynamoDBOperationConfig { QueryFilter = scs, }; AsyncSearch <Reply> response = context.QueryAsync <Reply>(replyId, cfg); IEnumerable <Reply> latestReplies = await response.GetRemainingAsync(); Console.WriteLine("\nReplies in last 15 days:"); foreach (Reply r in latestReplies) { Console.WriteLine($"{r.Id}\t{r.PostedBy}\t{r.Message}\t{r.ReplyDateTime}"); } }
/// <summary> /// PollyNotes-ListFunction /// /// This lambda function is integrated with the following API methods: /// /notes/GET /// /// This function does the following: /// 1. Takes a JSON payload from API gateway and converts it into a Note POCO <see cref="Note"/> /// 2. Queries DynamoDB based on that payload using the QueryAsync feature /// 3. Returns the List of Note found /// </summary> /// <param name="note">POCO of Note from the JSON payload from API GW to Lambda. In this case, it will only have the userId set</param> /// <param name="context">Lambda context</param> /// <returns>List of Note from the Query to DynamoDB based on the userId</returns> public List <Note> FunctionHandler(Note note, ILambdaContext context) { // The note object only contains the userId as it's the only parameter sent in the /notes/GET // { // "userId": "..." // } Console.WriteLine("Initiating PollyNotes-ListFunction..."); // Create the DynamoDB client and the Context for Object Persistence Model var dbClient = new AmazonDynamoDBClient(); var dbContext = new DynamoDBContext(dbClient); // Use the QueryAsync method to issue a query to DynamoDB based on the userId AsyncSearch <Note> noteQuery = dbContext.QueryAsync <Note>(note.userId); // Retrieve all of the notes based on the Query from DynamoDB using GetRemainingAsync and wait var list = noteQuery.GetRemainingAsync(); list.Wait(); // Return the list of Note (currently returning an empty list) return((list.Exception == null)? list.Result : new List <Note>()); }
/// <summary> /// Queries for replies posted within a specific time period. /// </summary> /// <param name="context">The DynamoDB context used to perform the query.</param> /// <param name="forumName">The name of the ofrum we're interested in.</param> /// <param name="threadSubject">Information about the subject we are /// interested in.</param> public static async Task FindRepliesPostedWithinTimePeriod( IDynamoDBContext context, string forumName, string threadSubject) { string forumId = forumName + "#" + threadSubject; Console.WriteLine("\nReplies posted within time period:"); DateTime startDate = DateTime.UtcNow - TimeSpan.FromDays(30); DateTime endDate = DateTime.UtcNow - TimeSpan.FromDays(1); List <object> times = new List <object>(); times.Add(startDate); times.Add(endDate); List <ScanCondition> scs = new List <ScanCondition>(); var sc = new ScanCondition("LastPostedBy", ScanOperator.Between, times.ToArray()); scs.Add(sc); var cfg = new DynamoDBOperationConfig { QueryFilter = scs }; AsyncSearch <Reply> response = context.QueryAsync <Reply>(forumId, cfg); IEnumerable <Reply> repliesInAPeriod = await response.GetRemainingAsync(); foreach (Reply r in repliesInAPeriod) { Console.WriteLine("{r.Id}\t{r.PostedBy}\t{r.Message}\t{r.ReplyDateTime}"); } }
public List <T> GetScan <T>(IEnumerable <ScanCondition> scan) where T : class { AsyncSearch <T> search = _Context.ScanAsync <T>(scan); Task <List <T> > item = search.GetRemainingAsync(); return(item.Result); }
public async Task <IEnumerable <TenTwentyAgency> > GetAsync(CancellationToken cancellationToken = default(CancellationToken)) { DynamoDBContext context = new DynamoDBContext(Settings.AmazonDynamoDBClient); AsyncSearch <TenTwentyAgency> search = context.ScanAsync <TenTwentyAgency>(Enumerable.Empty <ScanCondition>(), null); List <TenTwentyAgency> result = await search.GetRemainingAsync(cancellationToken); return(result); }
private static async Task <List <T> > GetAllAsync <T>(AsyncSearch <T> searchResult) { List <T> result; do { result = await searchResult.GetRemainingAsync().ConfigureAwait(false); } while (!searchResult.IsDone); return(result); }
public async Task <List <T> > GetAsyncSearchResult <T>(AsyncSearch <T> asyncSearch, CancellationToken cancellationToken) { var results = await asyncSearch.GetNextSetAsync(cancellationToken); while (!asyncSearch.IsDone && !cancellationToken.IsCancellationRequested) { results.AddRange(await asyncSearch.GetRemainingAsync(cancellationToken)); } return(results); }
/// <summary> /// Get a role by its normalized name. /// </summary> /// <param name="normalizedName">Normalized role name</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <DynamoDBRole> GetRoleByName(string normalizedName, CancellationToken cancellationToken) { List <ScanCondition> conditionList = new List <ScanCondition>(); conditionList.Add(new ScanCondition("NormalizedName", ScanOperator.Equal, normalizedName)); AsyncSearch <DynamoDBRole> Roles = _context.ScanAsync <DynamoDBRole>( conditionList, _roleStoreDBConfig ); List <DynamoDBRole> RolesList = await Roles.GetRemainingAsync(cancellationToken); return(RolesList.FirstOrDefault()); }
/// <summary> /// Search for users by any of their attributes /// </summary> /// <param name="key">Name of the attribute</param> /// <param name="expectedValue">Value that the attribute will have</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <DynamoDBUser> GetUserByAttribute(string key, string expectedValue, CancellationToken cancellationToken) { List <ScanCondition> conditionList = new List <ScanCondition>(); conditionList.Add(new ScanCondition(key, ScanOperator.Equal, expectedValue)); AsyncSearch <DynamoDBUser> users = _context.ScanAsync <DynamoDBUser>( conditionList, _userStoreDBConfig ); List <DynamoDBUser> usersList = await users.GetRemainingAsync(cancellationToken); return(usersList.FirstOrDefault()); }
public async Task <APIGatewayProxyResponse> Read(APIGatewayProxyRequest request, ILambdaContext context) { var response = new APIGatewayProxyResponse(); try { DynamoDBContext dbContext = new DynamoDBContext(new AmazonDynamoDBClient(RegionEndpoint.APSoutheast2)); AsyncSearch <Canvas> search = dbContext.ScanAsync <Canvas>(Enumerable.Empty <ScanCondition>(), null); List <Canvas> result = await search.GetRemainingAsync(); //List<Canvas> list = new List<Canvas>(); //foreach (Canvas item in result) //{ // Canvas canvas = item; // string back = await GetS3Object(item.LayoutBackContent, context); // canvas.LayoutBackContent = back; // string front = await GetS3Object(item.LayoutFrontContent, context); // canvas.LayoutFrontContent = front; // list.Add(canvas); //} //context.Logger.Log(JsonConvert.SerializeObject(result)); //AmazonDynamoDBClient client = new AmazonDynamoDBClient(RegionEndpoint.APSoutheast2); //var req = new ScanRequest //{ // TableName = "identityONE_Card_Layouts", // ProjectionExpression = "ID, Name, LastModifiedDatetime" //}; //var resp = await client.ScanAsync(req); //foreach (Dictionary<string, AttributeValue> item in resp.Items) //{ // // Process the result. // context.Logger.Log(JsonConvert.SerializeObject(item)); //} response.StatusCode = (int)HttpStatusCode.OK; response.Body = JsonConvert.SerializeObject(result); response.Headers = new Dictionary <string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } }; } catch (Exception ex) { return(ReturnResponse(ex)); } return(response); }
protected async Task <TenTwentyResultSet <T> > ProtectedGetAsync(Guid agencyId, CancellationToken cancellationToken = default(CancellationToken)) { DynamoDBContext context = new DynamoDBContext(Settings.AmazonDynamoDBClient); AsyncSearch <T> result = context.QueryAsync <T>(agencyId.ToString(), QueryOperator.BeginsWith, new[] { prefix }); TenTwentyResultSet <T> resultSet = new TenTwentyResultSet <T>(); resultSet.Results = await result.GetRemainingAsync(cancellationToken); resultSet.ContinuationToken = null; resultSet.IsComplete = true; return(resultSet); }
/// <summary> /// Get users who are in a role. /// </summary> /// <param name="roleName">Normalized role name</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <List <DynamoDBUser> > GetUsersByRole(string roleName, CancellationToken cancellationToken) { List <ScanCondition> conditionList = new List <ScanCondition>(); conditionList.Add(new ScanCondition("Roles", ScanOperator.Contains, roleName)); AsyncSearch <DynamoDBUser> users = _context.ScanAsync <DynamoDBUser>( conditionList, _userStoreDBConfig ); List <DynamoDBUser> usersList = await users.GetRemainingAsync(cancellationToken); return(usersList); }
public async Task <IEnumerable <T> > GetAll() { ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("Id", ScanOperator.NotEqual, 0); ScanOperationConfig soc = new ScanOperationConfig { Filter = scanFilter }; AsyncSearch <T> search = _context.FromScanAsync <T>(soc); return(await search.GetRemainingAsync()); }
/// <summary> /// Get a user by one of the social logins they have used with the site /// </summary> /// <param name="loginProvider">Name of the provider</param> /// <param name="providerKey">Unique key identifying the user</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <DynamoDBUser> GetUserByLogin(string loginProvider, string providerKey, CancellationToken cancellationToken) { List <ScanCondition> conditionList = new List <ScanCondition>(); conditionList.Add(new ScanCondition("LoginProviders", ScanOperator.Contains, loginProvider)); conditionList.Add(new ScanCondition("LoginProviderKeys", ScanOperator.Contains, providerKey)); AsyncSearch <DynamoDBUser> users = _context.ScanAsync <DynamoDBUser>( conditionList, _userStoreDBConfig ); List <DynamoDBUser> usersList = await users.GetRemainingAsync(cancellationToken); return(usersList.FirstOrDefault()); }
/// <summary> /// Get all users with the provided claim /// </summary> /// <param name="claim">The claim in question</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <List <DynamoDBUser> > GetUsersByClaim(Claim claim, CancellationToken cancellationToken) { List <ScanCondition> conditionList = new List <ScanCondition>(); conditionList.Add(new ScanCondition("ClaimTypes", ScanOperator.Contains, claim.Type)); conditionList.Add(new ScanCondition("ClaimValues", ScanOperator.Contains, claim.Value)); AsyncSearch <DynamoDBUser> users = _context.ScanAsync <DynamoDBUser>( conditionList, _userStoreDBConfig ); List <DynamoDBUser> usersList = await users.GetRemainingAsync(cancellationToken); return(usersList); }
public async void listCartItems(List <ShoppingCart> dataCartItems, GridLayout grdShoppingCart) { dbConfig.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/"; dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com"; dbConfig.RegionEndpoint = RegionEndpoint.USEast1; AmazonDynamoDBClient dynDBClient = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint); //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/"; dynDBClient.Config.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamodb/"; dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1; DynamoDBContext dynContext = new DynamoDBContext(dynDBClient); AsyncSearch <ShoppingCart> listCartItems = dynContext.FromScanAsync <ShoppingCart>(new ScanOperationConfig() { ConsistentRead = true }); dataCartItems = await listCartItems.GetRemainingAsync(); var theCart = from aCartItem in dataCartItems where aCartItem.CustomerFname == strCustFName && aCartItem.CustomerLname == strCustLName && aCartItem.CheckedOut == false select aCartItem; grdShoppingCart.RemoveAllViews(); foreach (ShoppingCart cartItem in theCart) { CheckBox tvCartItem = new CheckBox(this); string strCartItemDesc = cartItem.ProductDescription; double dblCartItemUnitPrice = cartItem.UnitPrice; int iCartItemQuant = cartItem.Quantity; double dblCartItemTotalCost = cartItem.TotalCost; tvCartItem.Text = string.Format("{0} qty. {1} @ ${2} = {3}", strCartItemDesc, iCartItemQuant, dblCartItemUnitPrice, dblCartItemTotalCost); tvCartItem.SetTextSize(Android.Util.ComplexUnitType.Dip, 10f); tvCartItem.SetTextColor(Android.Graphics.Color.Black); tvCartItem.SetBackgroundColor(Android.Graphics.Color.White); tvCartItem.SetPadding(20, 5, 20, 5); tvCartItem.TextAlignment = TextAlignment.ViewStart; tvCartItem.SetWidth(1200); tvCartItem.SetBackgroundResource(Resource.Drawable.StoreName); grdShoppingCart.AddView(tvCartItem); } dblTotalPurchase = dataCartItems.Sum <ShoppingCart>(x => x.TotalCost); }
/// <summary> /// PollyNotes-ListFunction /// /// This lambda function is integrated with the following API methods: /// /notes/GET /// /// This function does the following: /// /// 1. Takes a JSON payload from API gateway and converts it into a Note POCO <see cref="Note"/> /// 2. Queries DynamoDB based on that payload using the QueryAsync feature /// 3. Returns the List of Note found /// </summary> /// <param name="note">POCO of Note from the JSON payload from API GW to Lambda. In this case, it will only have the userId set</param> /// <param name="context">Lambda context</param> /// <returns>List of Note from the Query to DynamoDB based on the userId</returns> public List <Note> FunctionHandler(Note note, ILambdaContext context) { // The note object only contains the userId as it's the only parameter sent in the /notes/GET // { // "userId": "..." // } Console.WriteLine("Initiating PollyNotes-ListFunction..."); Console.WriteLine("Note received: " + JsonConvert.SerializeObject(note)); // Create the DynamoDB client and the Context for Object Persistence Model AmazonDynamoDBClient client = new AmazonDynamoDBClient(); DynamoDBContext ddbcontext = new DynamoDBContext(client); // Use the QueryAsync method to issue a query to DynamoDB based on the userId // We are using an Async command due to the .netcore SDK which doesn't support sync invokes // We are using the Note POCO defined with the Object Persistence Model so all the data // will be mapped to the right entries. The Table name is also defined in the POCO AsyncSearch <Note> noteQuery = ddbcontext.QueryAsync <Note>(note.userId); // Retrieve all of the notes based on the Query from DynamoDB and wait Task <List <Note> > listTask = noteQuery.GetRemainingAsync(); listTask.Wait(); // Once the list has been fetched entirely, check for Exceptions. // If there are no Exceptions if (listTask.Exception == null) { Console.WriteLine("Successfully executed QueryAsync with userId: " + note.userId); // Log the Notes found Console.WriteLine("Notes found in DynamoDB: " + JsonConvert.SerializeObject(listTask.Result)); // Return the list return(listTask.Result); } else { // There was an exception, log the entry data and the exception Console.WriteLine("Unable to QueryAsync note with userId: " + note.userId); Console.WriteLine(listTask.Exception); // Return an empty list return(new List <Note>()); } }
public async Task <List <T> > LoadAll <T>(Dictionary <string, object>?conditions = null) where T : EntryBase, new() { if (this.context == null) { throw new Exception("Database is not connected"); } try { AsyncSearch <T> search = this.context.ScanAsync <T>(ToScanConditions(conditions), this.operationConfig); return(await search.GetRemainingAsync()); } catch (ResourceNotFoundException) { throw new Exception("Database table not found. This may be caused by new tables not propagating immediately."); } }
public async Task QueryTODOListAsync() { Console.WriteLine("----- Executing Query -----"); #region datamodel_construct_query AsyncSearch <TODOList> search = this.Context.QueryAsync <TODOList>("dm-testuser"); var lists = await search.GetRemainingAsync(); Console.WriteLine($"Total lists found: {lists.Count}"); foreach (var list in lists) { Console.WriteLine($"List {list.Name}"); foreach (var task in list.Items) { Console.WriteLine($"\t{task.Description}"); } } #endregion Console.WriteLine(); }
/// <summary> /// Queries the DynamoDB ProductCatalog table for products costing less /// than zero. /// </summary> /// <param name="context">The DynamoDB context object used to perform the /// query.</param> public static async Task FindProductsPricedLessThanZero(IDynamoDBContext context) { int price = 0; List <ScanCondition> scs = new List <ScanCondition>(); var sc1 = new ScanCondition("Price", ScanOperator.LessThan, price); var sc2 = new ScanCondition("ProductCategory", ScanOperator.Equal, "Book"); scs.Add(sc1); scs.Add(sc2); AsyncSearch <Book> response = context.ScanAsync <Book>(scs); IEnumerable <Book> itemsWithWrongPrice = await response.GetRemainingAsync(); Console.WriteLine("\nFindProductsPricedLessThanZero: Printing result....."); foreach (Book r in itemsWithWrongPrice) { Console.WriteLine($"{r.Id}\t{r.Title}\t{r.Price}\t{r.Isbn}"); } }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.ItemsLayout); strUserZip = this.Intent.GetStringExtra("UserZipCode"); strSelectedStore = this.Intent.GetStringExtra("SelectedStore"); if (this.Intent.GetStringExtra("CustomerFName") != "") { strCustFName = this.Intent.GetStringExtra("CustomerFName"); strCustLName = this.Intent.GetStringExtra("CustomerLName"); } GridLayout grdItems = FindViewById <GridLayout>(Resource.Id.grdItems); ImageButton imgAddItem = FindViewById <ImageButton>(Resource.Id.imgAddItem); TextView tvSelectedItemName = FindViewById <TextView>(Resource.Id.tvSelectedItemName); Button btnViewWebSearch = FindViewById <Button>(Resource.Id.btnViewWebSearch); Button btnToShoppingCart = FindViewById <Button>(Resource.Id.btnToShoppingCart); Button btnBack = FindViewById <Button>(Resource.Id.btnBack); dbConfig.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/"; dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com"; dbConfig.RegionEndpoint = RegionEndpoint.USEast1; AmazonDynamoDBClient dynDBClient = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint); //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/"; dynDBClient.Config.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamodb/"; dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1; DynamoDBContext dynContext = new DynamoDBContext(dynDBClient); AsyncSearch <ItemCategories> listItems = dynContext.FromScanAsync <ItemCategories>(new ScanOperationConfig() { ConsistentRead = true }); List <ItemCategories> dataItems = await listItems.GetRemainingAsync(); var theItems = from anItem in dataItems where anItem.CategoryName != "none" select anItem; this.listTheItems(dataItems, tvSelectedItemName, grdItems); strSelectedItem = ""; tvSelectedItemName.Text = ""; btnViewWebSearch.Click += (sender, e) => { Uri uriSearch = new Uri(string.Format("http://www.google.com/search?q={0}+{1}+product+categories+{2}", strUserZip, strSelectedStore, strSelectedItem)); WebView webSearchItems = new WebView(this); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriSearch); request.Method = "GET"; request.AllowWriteStreamBuffering = false; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); string returnString = response.StatusCode.ToString(); // editText1.Text = responseText; // Toast.MakeText(this, responseText, ToastLength.Long).Show(); webSearchItems.LoadUrl(uriSearch.ToString()); }; btnToShoppingCart.Click += (sender, e) => { if (strSelectedStore.Trim() == "") { var dlgBlankStore = new AlertDialog.Builder(this); dlgBlankStore.SetMessage("Please select an item category!"); dlgBlankStore.SetNeutralButton("OK", delegate { }); dlgBlankStore.Show(); } else { Intent intentCart = new Intent(this, typeof(ShoppingCartActivity)); intentCart.PutExtra("CustomerFName", strCustFName); intentCart.PutExtra("CustomerLName", strCustLName); intentCart.PutExtra("SelectedStore", strSelectedStore); intentCart.PutExtra("ProductType", strSelectedItem); intentCart.PutExtra("UserZipCode", strUserZip); StartActivity(intentCart); } }; btnBack.Click += (sender, e) => { Intent intentStores = new Intent(this, typeof(StoresActivity)); intentStores.PutExtra("UserZipCode", strUserZip); StartActivity(intentStores); }; imgAddItem.Click += (sender, e) => { var dlgAddNewItem = new AlertDialog.Builder(this); dlgAddNewItem.SetTitle("ADD A NEW ITEM"); dlgAddNewItem.SetMessage("Please Enter a Product Type"); EditText edtNewItemName = new EditText(this); //edtNewItemName.SetWidth(600); // grdNewStoreInfo.AddView(edtNewStoreName); dlgAddNewItem.SetView(edtNewItemName); dlgAddNewItem.SetPositiveButton("OK", delegate { string strNewItemName = edtNewItemName.Text; var reqScanItems = new ScanRequest { TableName = "ItemCategories" }; var respScanItems = dynDBClient.ScanAsync(reqScanItems); int iItemCount = respScanItems.Result.Count; Table tblTheItems = Table.LoadTable(dynDBClient, "ItemCategories"); Document docNewItem = new Document(); docNewItem["IcID"] = iItemCount.ToString(); docNewItem["CategoryName"] = strNewItemName; tblTheItems.PutItemAsync(docNewItem); this.listTheItems(dataItems, tvSelectedItemName, grdItems); }); dlgAddNewItem.SetNegativeButton("CANCEL", delegate { }); dlgAddNewItem.Show(); }; }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.DeliveryNotification); dbConfig.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/"; dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com"; dbConfig.RegionEndpoint = RegionEndpoint.USEast1; EditText edtDeliveryMessage = FindViewById <EditText>(Resource.Id.edtDeliveryMessage); AmazonDynamoDBClient dynDBClient = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint); GridLayout grdDeliveryNotification = FindViewById <GridLayout>(Resource.Id.grdDeliveryNotification); //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/"; dynDBClient.Config.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamodb/"; dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1; DynamoDBContext dynContext = new DynamoDBContext(dynDBClient); Button btnHome = FindViewById <Button>(Resource.Id.btnHome); AsyncSearch <DeliveryNotification> listDeliveries = dynContext.FromScanAsync <DeliveryNotification>(new ScanOperationConfig() { ConsistentRead = true }); List <DeliveryNotification> lstDataDeliveries = await listDeliveries.GetRemainingAsync(); AsyncSearch <CreditCardNotification> listCCNotification = dynContext.FromScanAsync <CreditCardNotification>(new ScanOperationConfig() { ConsistentRead = true }); List <CreditCardNotification> lstDataCCNotification = await listCCNotification.GetRemainingAsync(); var theDeliveries = from aDelivery in lstDataDeliveries where aDelivery.NotifyID == 0 select aDelivery; int newDeliveryCount = 0; foreach (DeliveryNotification deliv in lstDataDeliveries) { if (deliv.DeliveryItemID == 0) { break; } TextView tvSubject = new TextView(this); tvSubject.Text = string.Concat(deliv.CustomerName, " ", deliv.ProductDescription, " ", deliv.DeliveryDate); tvSubject.SetBackgroundResource(Resource.Drawable.StoreName); tvSubject.SetTextColor(Android.Graphics.Color.Black); if (deliv.NotifyID == 0) { ++newDeliveryCount; tvSubject.SetTypeface(Android.Graphics.Typeface.Default, Android.Graphics.TypefaceStyle.Bold); } tvSubject.Click += (sender, e) => { CreditCardNotification ccPurchaseQuery = lstDataCCNotification.Find(x => x.CardNumber == deliv.CreditCardNum && x.ItemDescription == deliv.ProductDescription && x.Amount == deliv.Cost); string strMerchant = ccPurchaseQuery.Merchant; string strCCNum = ccPurchaseQuery.CardNumber; StringBuilder sbMessage = new StringBuilder(); sbMessage.Append(deliv.CustomerName + " ordered " + deliv.ProductDescription + " from " + strMerchant); sbMessage.AppendLine(" for " + deliv.Cost.ToString() + " to be delivered at "); sbMessage.AppendLine(deliv.CustomerAddress + ", " + deliv.CustomerCity + ", " + deliv.CustomerState + ", " + deliv.CustomerZip); sbMessage.AppendLine(" on " + deliv.DeliveryDate + " time: " + deliv.DeliveryTime + ", CC#" + strCCNum); edtDeliveryMessage.Text = sbMessage.ToString(); // edtDeliveryMessage.Text = string.Format("{0} ordered {1} from {2} for {3} to be delivered at {4}, {5}, {6}, {7} on {8}, Time: {9) CC# {10}", deliv.CustomerName, deliv.ProductDescription,strMerchant,deliv.Cost, deliv.CustomerAddress, deliv.CustomerCity, deliv.CustomerState, deliv.CustomerZip,deliv.DeliveryDate, deliv.DeliveryTime,strCCNum); }; grdDeliveryNotification.AddView(tvSubject); } if (newDeliveryCount > 0) { var dlgNewDeliveryNote = new AlertDialog.Builder(this); dlgNewDeliveryNote.SetMessage("You have new orders to deliver."); dlgNewDeliveryNote.SetNeutralButton("OK", delegate { }); dlgNewDeliveryNote.Show(); } btnHome.Click += (sender, e) => { var intentHomeScreen = new Intent(this, typeof(GoShoppingActivity)); StartActivity(intentHomeScreen); }; }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.ShoppingCartLayout); dbConfig.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/"; dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com"; dbConfig.RegionEndpoint = RegionEndpoint.USEast1; AmazonDynamoDBClient dynDBClient = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint); //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/"; dynDBClient.Config.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamodb/"; dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1; DynamoDBContext dynContext = new DynamoDBContext(dynDBClient); AsyncSearch <ShoppingCart> listDataCartItems = dynContext.FromScanAsync <ShoppingCart>(new ScanOperationConfig() { ConsistentRead = true }); List <ShoppingCart> dataCartItems = await listDataCartItems.GetRemainingAsync(); Button btnCheckout = FindViewById <Button>(Resource.Id.btnCheckout); Button btnBack = FindViewById <Button>(Resource.Id.btnBack); Button btnEnterOrder = FindViewById <Button>(Resource.Id.btnEnterOrder); GridLayout grdOrderEntry = FindViewById <GridLayout>(Resource.Id.grdOrderEntry); TextView tvCustName = FindViewById <TextView>(Resource.Id.tvCustName); EditText edtItemDescription = FindViewById <EditText>(Resource.Id.edtItemDescription); EditText edtPrice = FindViewById <EditText>(Resource.Id.edtPrice); EditText edtQuant = FindViewById <EditText>(Resource.Id.edtQuant); DateTime dtOrderDate = DateTime.Today; strOrderDate = dtOrderDate.ToString("MM/dd/yyyy"); strCustFName = this.Intent.GetStringExtra("CustomerFName"); strCustLName = this.Intent.GetStringExtra("CustomerLName"); strStoreName = this.Intent.GetStringExtra("SelectedStore"); strZipCode = this.Intent.GetStringExtra("UserZipCode"); strSelectItem = this.Intent.GetStringExtra("ProductType"); var dlgCustomerName = new AlertDialog.Builder(this); GridLayout grdShoppingCart = FindViewById <GridLayout>(Resource.Id.grdShoppingCart); GridLayout grdCustName = new GridLayout(this); grdCustName.RowCount = 2; grdCustName.ColumnCount = 2; TextView tvFName = new TextView(this); tvFName.Text = "First Name:"; grdCustName.AddView(tvFName); EditText edtFName = new EditText(this); grdCustName.AddView(edtFName); TextView tvLName = new TextView(this); tvLName.Text = "Last Name"; grdCustName.AddView(tvLName); EditText edtLName = new EditText(this); grdCustName.AddView(edtLName); dlgCustomerName.SetTitle("PLEASE ENTER YOUR NAME"); dlgCustomerName.SetView(grdCustName); dlgCustomerName.SetPositiveButton("OK", delegate { strCustFName = edtFName.Text; strCustLName = edtLName.Text; tvCustName.Text = string.Concat(strCustFName, " ", strCustLName); listCartItems(dataCartItems, grdShoppingCart); }); dlgCustomerName.SetNegativeButton("CANCEL", delegate { }); dlgCustomerName.Show(); var theCart = from aCartItem in dataCartItems where aCartItem.CustomerFname == strCustFName && aCartItem.CustomerLname == strCustLName && aCartItem.CheckedOut == false select aCartItem; TextView tvCustStore = FindViewById <TextView>(Resource.Id.tvCustStore); tvCustStore.Text = strStoreName; listCartItems(dataCartItems, grdShoppingCart); btnCheckout.Click += (sender, e) => { var dlgCheckout = new AlertDialog.Builder(this); dlgCheckout.SetMessage("Are you sure you want to check out your order?"); GridLayout grdPurchase = new GridLayout(this); grdPurchase.ColumnCount = 1; grdPurchase.RowCount = 10; RadioGroup rgCreditCards = new RadioGroup(this); RadioButton rbVisa = new RadioButton(this); rbVisa.Text = "VISA"; rgCreditCards.AddView(rbVisa); RadioButton rbMasterCard = new RadioButton(this); rbMasterCard.Text = "MASTER CARD"; rgCreditCards.AddView(rbMasterCard); RadioButton rbDiscover = new RadioButton(this); rbDiscover.Text = "DISCOVER"; rgCreditCards.AddView(rbDiscover); RadioButton rbAmEx = new RadioButton(this); rbAmEx.Text = "AMERICAN EXPRESS"; rgCreditCards.AddView(rbAmEx); grdPurchase.AddView(rgCreditCards); TextView tvCCPrompt = new TextView(this); tvCCPrompt.Text = "YOUR CREDIT CARD NUMBER:"; grdPurchase.AddView(tvCCPrompt); EditText edtCCNum = new EditText(this); grdPurchase.AddView(edtCCNum); TextView tvExpDate = new TextView(this); tvExpDate.Text = "EXPIRATION DATE (mmyy):"; EditText edtExpDate = new EditText(this); grdPurchase.AddView(tvExpDate); grdPurchase.AddView(edtExpDate); TextView tvVerifyCode = new TextView(this); tvVerifyCode.Text = "YOUR THREE-DIGIT VERIFICATION CODE:"; EditText edtVerifyCode = new EditText(this); grdPurchase.AddView(tvVerifyCode); grdPurchase.AddView(edtVerifyCode); dlgCheckout.SetView(grdPurchase); string strCCName = ""; bool boolCCSelected = false; //Toast.MakeText(this, grdPurchase.ChildCount.ToString(), ToastLength.Long).Show(); dlgCheckout.SetPositiveButton("OK", async delegate { // EditText edtTheNumber = (EditText)grdPurchase.GetChildAt(2); string strCCNum = edtCCNum.Text; string strExpDate = edtExpDate.Text; string strVerifyCode = edtVerifyCode.Text; string strExpDatePattern = @"^(0[1-9]|1[012])\d{2}$"; for (int iCCN = 0; iCCN < rgCreditCards.ChildCount; iCCN++) { RadioButton rbCC = (RadioButton)rgCreditCards.GetChildAt(iCCN); if (rbCC.Checked) { boolCCSelected = true; strCCName = rbCC.Text; break; } } if (!boolCCSelected) { Toast.MakeText(this, "PLEASE SELECT A CREDIT CARD", ToastLength.Long).Show(); } else if (strCCNum.Trim() == "") { Toast.MakeText(this, "PLEASE ENTER YOUR CREDIT INFORMATION", ToastLength.Long).Show(); } else if (Regex.IsMatch(strExpDate, strExpDatePattern) == false) { Toast.MakeText(this, "PLEASE ENTER YOUR EXPIRATION DATE IN FORM mmyy", ToastLength.Long).Show(); } else { AsyncSearch <CreditCard> listPurchases = dynContext.FromScanAsync <CreditCard>(new ScanOperationConfig() { ConsistentRead = true }); List <CreditCard> listDataPurchases = await listPurchases.GetRemainingAsync(); int iCountAllPurchases = listDataPurchases.Count; listDataCartItems = dynContext.FromScanAsync <ShoppingCart>(new ScanOperationConfig() { ConsistentRead = true }); dataCartItems = await listDataCartItems.GetRemainingAsync(); theCart = from aCartItem in dataCartItems where aCartItem.CustomerFname == strCustFName && aCartItem.CustomerLname == strCustLName && aCartItem.CheckedOut == false && aCartItem.OrderID != "0" select aCartItem; Table tblShoppingCart = Table.LoadTable(dynDBClient, "ShoppingCart"); Table tblCreditCard = Table.LoadTable(dynDBClient, "CreditCard"); foreach (ShoppingCart aCartItem in theCart) { Document docCartItem = new Document(); Document docPurchase = new Document(); docCartItem["OrderID"] = aCartItem.OrderID; docCartItem["CheckedOut"] = 1; docPurchase["ChargeID"] = (iCountAllPurchases++).ToString(); docPurchase["CardNumber"] = strCCNum; docPurchase["Amount"] = aCartItem.TotalCost; docPurchase["CardName"] = strCCName; docPurchase["CustomerName"] = string.Concat(strCustFName, " ", strCustLName); docPurchase["Expiration"] = strExpDate; docPurchase["ItemDescription"] = aCartItem.ProductDescription; docPurchase["Verification"] = strVerifyCode; docPurchase["Merchant"] = aCartItem.StoreName; docPurchase["PurchaseDate"] = strOrderDate; docPurchase["NewCharge"] = 1; await tblCreditCard.PutItemAsync(docPurchase); // await tblShoppingCart.UpdateItemAsync(docCartItem); await tblShoppingCart.DeleteItemAsync(docCartItem); } Intent intentDeliveryPickup = new Intent(this, typeof(DeliveryPickupActivity)); StartActivity(intentDeliveryPickup); } }); dlgCheckout.SetNegativeButton("NO", delegate { }); dlgCheckout.Show(); }; btnEnterOrder.Click += async(sender, e) => { AsyncSearch <ShoppingCart> listUpdateDataCartItems = dynContext.FromScanAsync <ShoppingCart>(new ScanOperationConfig() { ConsistentRead = true }); List <ShoppingCart> dataUpdateCartItems = await listUpdateDataCartItems.GetRemainingAsync(); int iOrderCount = dataUpdateCartItems.Count; string strDescription = edtItemDescription.Text.Trim(); string strPrice = edtPrice.Text.Trim(); string strQuant = edtQuant.Text.Trim(); if (strDescription == "") { Toast.MakeText(this, "PLEASE ENTER A PRODUCT DESCRIPTION", ToastLength.Long).Show(); return; } Double dblNum = 0.00; if (Double.TryParse(strPrice, out dblNum) == false) { Toast.MakeText(this, "PLEASE ENTER PRICE AS A REAL NUMBER", ToastLength.Long).Show(); return; } int iNum = 0; if (int.TryParse(strQuant, out iNum) == false) { Toast.MakeText(this, "PLEASE ENTER QUANTITY AS AN INTEGER NUMBER", ToastLength.Long).Show(); return; } else if (Convert.ToInt32(strQuant) <= 0) { Toast.MakeText(this, "PLEASE ENTER A POSITIVE NUMBER (>=1)", ToastLength.Long).Show(); return; } Table tblCart = Table.LoadTable(dynDBClient, "ShoppingCart"); Document docMerchandise = new Document(); double dblUnitPrice = Convert.ToDouble(strPrice); int iQuant = Convert.ToInt32(strQuant); double dblTotalCost = Convert.ToDouble(iQuant) * dblUnitPrice; docMerchandise["OrderID"] = iOrderCount.ToString(); docMerchandise["ProductDescription"] = strDescription; docMerchandise["CustomerFname"] = strCustFName; docMerchandise["CustomerLname"] = strCustLName; docMerchandise["StoreName"] = strStoreName; docMerchandise["UnitPrice"] = dblUnitPrice; docMerchandise["Quantity"] = iQuant; docMerchandise["TotalCost"] = dblTotalCost; docMerchandise["OrderDate"] = strOrderDate; docMerchandise["CheckedOut"] = 0; await tblCart.PutItemAsync(docMerchandise); listCartItems(dataCartItems, grdShoppingCart); // double dblRunningTotal += dblTotalCost; edtItemDescription.Text = ""; edtPrice.Text = ""; edtQuant.Text = ""; // dblTotalPurchase = dblRunningTotal; }; btnBack.Click += (sender, e) => { Intent intentItems = new Intent(this, typeof(ItemsActivity)); intentItems.PutExtra("CustomerFname", strCustFName); intentItems.PutExtra("CustomerLname", strCustLName); intentItems.PutExtra("SelectedStore", strStoreName); intentItems.PutExtra("UserZipCode", strZipCode); intentItems.PutExtra("OrderDate", strOrderDate); intentItems.PutExtra("ProductType", strSelectItem); StartActivity(intentItems); }; }
public Task <List <T> > GetRemainingAsync(CancellationToken cancellationToken) { return(_asyncSearch.GetRemainingAsync(cancellationToken)); }
/// <summary> /// Method to respond to an API request and retrieve the data from DynamoDB with /// possible filters included /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public async Task <APIGatewayProxyResponse> GetData(APIGatewayProxyRequest request, ILambdaContext context) { this._context = context; context.LogInfo($"Get data request\r\n{JsonConvert.SerializeObject(request)}"); try { GetDashboardEventsRequest req = new GetDashboardEventsRequest(request.QueryStringParameters); List <ScanCondition> conditions = new List <ScanCondition>(); if (req.Start > 0) { conditions.Add(new ScanCondition("Date", ScanOperator.GreaterThanOrEqual, ServiceUtilities.ConvertFromUnixTimestamp(req.Start))); } if (req.End > 0) { conditions.Add(new ScanCondition("Date", ScanOperator.LessThanOrEqual, ServiceUtilities.ConvertFromUnixTimestamp(req.End))); } if (req.Regions != null && req.Regions.Any()) { conditions.Add(new ScanCondition("Region", ScanOperator.In, req.Regions.ToArray())); // Casting to Array is important } if (req.Services != null && req.Services.Any()) { conditions.Add(new ScanCondition("Service", ScanOperator.In, req.Services.ToArray())); // Casting to Array is important } AsyncSearch <DashboardEventParsed> search = ddbContext.ScanAsync <DashboardEventParsed>(conditions); IEnumerable <DashboardEventParsed> data = await search.GetRemainingAsync(); return(CreateResponse(data, req)); } catch (AggregateException e) { this._context.LogError(e); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.InternalServerError, Body = FlattenToJsonString(e), Headers = new Dictionary <string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } } }); } catch (Exception e) { this._context.LogError(e); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.InternalServerError, Body = JsonConvert.SerializeObject(e, new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }), Headers = new Dictionary <string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } } }); } }
private void TestHashRangeObjects() { // Create and save item Employee employee = new Employee { Name = "Alan", Age = 31, CompanyName = "Big River", CurrentStatus = Status.Active, Score = 120, ManagerName = "Barbara", InternalId = "Alan@BigRiver", Aliases = new List <string> { "Al", "Steve" }, Data = Encoding.UTF8.GetBytes("Some binary data"), }; var ex = new Exception(); AutoResetEvent ars = new AutoResetEvent(false); Context.SaveAsync(employee, (result) => { ex = result.Exception; ars.Set(); }, options); ars.WaitOne(); Assert.IsNull(ex); // Load item Employee retrieved = null; ex = new Exception(); Context.LoadAsync <Employee>(employee, (result) => { ex = result.Exception; retrieved = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.IsNull(ex); Assert.IsNotNull(retrieved); Assert.AreEqual(employee.Name, retrieved.Name); Assert.AreEqual(employee.Age, retrieved.Age); Assert.AreEqual(employee.CompanyName, retrieved.CompanyName); Assert.AreEqual(employee.CurrentStatus, retrieved.CurrentStatus); // Create and save new item employee.Name = "Chuck"; employee.Age = 30; employee.CurrentStatus = Status.Inactive; employee.Aliases = new List <string> { "Charles" }; employee.Data = Encoding.UTF8.GetBytes("Binary data"); employee.Score = 94; ex = new Exception(); Context.SaveAsync(employee, (result) => { ex = result.Exception; ars.Set(); }, options); ars.WaitOne(); Assert.IsNull(ex); // Load item ex = new Exception(); Context.LoadAsync <Employee>(employee, (result) => { ex = result.Exception; retrieved = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.IsNull(ex); Assert.AreEqual(employee.Name, retrieved.Name); Assert.AreEqual(employee.Age, retrieved.Age); Assert.AreEqual(employee.CompanyName, retrieved.CompanyName); Assert.AreEqual(employee.CurrentStatus, retrieved.CurrentStatus); Assert.AreEqual(employee.Data.Length, retrieved.Data.Length); // Create more items Employee employee2 = new Employee { Name = "Diane", Age = 40, CompanyName = "Madeira", Score = 140, ManagerName = "Eva", Data = new byte[] { 1, 2, 3 }, CurrentStatus = Status.Upcoming, InternalId = "Diane@Madeira", }; ex = new Exception(); Context.SaveAsync(employee2, (result) => { ex = result.Exception; ars.Set(); }, options); ars.WaitOne(); Assert.IsNull(ex); employee2.Age = 24; employee2.Score = 101; ex = new Exception(); Context.SaveAsync(employee2, (result) => { ex = result.Exception; ars.Set(); }, options); ars.WaitOne(); Assert.IsNull(ex); Context.LoadAsync <Employee>("Alan", 31, (result) => { retrieved = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(retrieved.Name, "Alan"); Context.LoadAsync(employee, (result) => { retrieved = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(retrieved.Name, "Chuck"); Context.LoadAsync(employee2, new DynamoDBOperationConfig { ConsistentRead = true }, (result) => { retrieved = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(retrieved.Name, "Diane"); Assert.AreEqual(retrieved.Age, 24); // Scan for all items List <Employee> employees = null; Context.ScanAsync <Employee>(new ScanCondition[] { }).GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(4, employees.Count); AsyncSearch <Employee> asyncSearch = null; // Query for items with Hash-Key = "Diane" Context.QueryAsync <Employee>("Diane", (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Query for items with Hash-Key = "Diane" and Range-Key > 30 Context.QueryAsync <Employee>("Diane", QueryOperator.GreaterThan, (result) => { asyncSearch = result.Result; ars.Set(); }, options, new object[] { 30 }); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(1, employees.Count); // Index Query // Query local index for items with Hash-Key = "Diane" Context.QueryAsync <Employee>("Diane", new DynamoDBOperationConfig { IndexName = "LocalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Query local index for items with Hash-Key = "Diane" and Range-Key = "Eva" Context.QueryAsync <Employee>("Diane", QueryOperator.Equal, new object[] { "Eva" }, new DynamoDBOperationConfig { IndexName = "LocalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Query global index for item with Hash-Key (Company) = "Big River" Context.QueryAsync <Employee>("Big River", new DynamoDBOperationConfig { IndexName = "GlobalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Query global index for item with Hash-Key (Company) = "Big River", with QueryFilter for CurrentStatus = Status.Active Context.QueryAsync <Employee>("Big River", new DynamoDBOperationConfig { IndexName = "GlobalIndex", QueryFilter = new List <ScanCondition> { new ScanCondition("CurrentStatus", ScanOperator.Equal, Status.Active) } }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(1, employees.Count); // Index Scan // Scan local index for items with Hash-Key = "Diane" Context.ScanAsync <Employee>( new List <ScanCondition> { new ScanCondition("Name", ScanOperator.Equal, "Diane") }, new DynamoDBOperationConfig { IndexName = "LocalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Scan local index for items with Hash-Key = "Diane" and Range-Key = "Eva" Context.ScanAsync <Employee>( new List <ScanCondition> { new ScanCondition("Name", ScanOperator.Equal, "Diane"), new ScanCondition("ManagerName", ScanOperator.Equal, "Eva") }, new DynamoDBOperationConfig { IndexName = "LocalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Scan global index for item with Hash-Key (Company) = "Big River" Context.ScanAsync <Employee>( new List <ScanCondition> { new ScanCondition("CompanyName", ScanOperator.Equal, "Big River") }, new DynamoDBOperationConfig { IndexName = "GlobalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(2, employees.Count); // Scan global index for item with Hash-Key (Company) = "Big River", with QueryFilter for CurrentStatus = Status.Active Context.ScanAsync <Employee>( new List <ScanCondition> { new ScanCondition("CompanyName", ScanOperator.Equal, "Big River"), new ScanCondition("CurrentStatus", ScanOperator.Equal, Status.Active) }, new DynamoDBOperationConfig { IndexName = "GlobalIndex" }, (result) => { asyncSearch = result.Result; ars.Set(); }, options); ars.WaitOne(); asyncSearch.GetRemainingAsync((result) => { employees = result.Result; ars.Set(); }, options); ars.WaitOne(); Assert.AreEqual(1, employees.Count); }
public async void listTheStores(List <RetailStores> dataStores, TextView tvSelectedStoreName, GridLayout grdStores) { dbConfig.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/"; dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com"; dbConfig.RegionEndpoint = RegionEndpoint.USEast1; AmazonDynamoDBClient dynDBClient = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint); //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/"; dynDBClient.Config.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamodb/"; dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1; DynamoDBContext dynContext = new DynamoDBContext(dynDBClient); AsyncSearch <RetailStores> listStores = dynContext.FromScanAsync <RetailStores>(new ScanOperationConfig() { ConsistentRead = true }); dataStores = await listStores.GetRemainingAsync(); var theStores = from store in dataStores where store.StoreName != "none" select store; grdStores.RemoveAllViews(); foreach (RetailStores store in theStores) { TextView tvStore = new TextView(this) { Id = View.GenerateViewId() }; tvStore.Text = store.StoreName; strSelectedStore = tvStore.Text; tvStore.SetTextColor(Android.Graphics.Color.Black); tvStore.SetBackgroundColor(Android.Graphics.Color.White); tvStore.SetPadding(20, 5, 20, 5); tvStore.TextAlignment = TextAlignment.ViewStart; tvStore.SetWidth(1200); tvStore.SetBackgroundResource(Resource.Drawable.StoreName); tvStore.Click += (sender, e) => { strSelectedStore = tvStore.Text; tvSelectedStoreName.Text = strSelectedStore; Uri uriSearch = new Uri(string.Format("http://www.google.com/search?q=list+stores+near+{0}+{1} ", strUserZip, strSelectedStore)); WebView webStores = new WebView(this); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriSearch); request.Method = "GET"; request.AllowWriteStreamBuffering = false; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); string returnString = response.StatusCode.ToString(); // editText1.Text = responseText; // Toast.MakeText(this, responseText, ToastLength.Long).Show(); webStores.LoadUrl(uriSearch.ToString()); }; grdStores.AddView(tvStore); } }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.StoresLayout); strUserZip = Intent.GetStringExtra("UserZipCode"); GridLayout grdStores = FindViewById <GridLayout>(Resource.Id.grdStores); ImageButton imgAddStore = FindViewById <ImageButton>(Resource.Id.imgAddStore); Button btnToItems = FindViewById <Button>(Resource.Id.btnToItems); Button btnViewWebSite = FindViewById <Button>(Resource.Id.btnViewWebSite); TextView tvSelectedStoreName = FindViewById <TextView>(Resource.Id.tvSelectedStoreName); dbConfig.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/"; dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com"; dbConfig.RegionEndpoint = RegionEndpoint.USEast1; AmazonDynamoDBClient dynDBClient = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint); //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/"; dynDBClient.Config.ServiceURL = "https://026821060357.signin.aws.amazon.com/console/dynamodb/"; dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1; DynamoDBContext dynContext = new DynamoDBContext(dynDBClient); AsyncSearch <RetailStores> listStores = dynContext.FromScanAsync <RetailStores>(new ScanOperationConfig() { ConsistentRead = true }); List <RetailStores> dataStores = await listStores.GetRemainingAsync(); this.listTheStores(dataStores, tvSelectedStoreName, grdStores); strSelectedStore = ""; btnViewWebSite.Click += (sender, e) => { Uri uriSearch = new Uri(string.Format("http://www.google.com/search?q=list+stores+near+{0}+{1} ", strUserZip, strSelectedStore)); WebView webStores = new WebView(this); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriSearch); request.Method = "GET"; request.AllowWriteStreamBuffering = false; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); string returnString = response.StatusCode.ToString(); // editText1.Text = responseText; // Toast.MakeText(this, responseText, ToastLength.Long).Show(); webStores.LoadUrl(uriSearch.ToString()); }; btnToItems.Click += (sender, e) => { Intent intentItems = new Intent(this, typeof(ItemsActivity)); intentItems.PutExtra("UserZipCode", strUserZip); intentItems.PutExtra("SelectedStore", strSelectedStore); var dlgToItemsScreen = new AlertDialog.Builder(this); if (strSelectedStore.Trim() == "") { dlgToItemsScreen.SetMessage("PLEASE SELECT A STORE!"); dlgToItemsScreen.SetNeutralButton("OK", delegate { }); } else { dlgToItemsScreen.SetTitle(string.Format("{0} in or near {1}", strSelectedStore, strUserZip)); dlgToItemsScreen.SetMessage(string.Format("This will take you to the Items screen based on your search\nfor {0} in/near your area, is this OK?", strSelectedStore, strUserZip)); dlgToItemsScreen.SetPositiveButton("OK", delegate { StartActivity(intentItems); }); dlgToItemsScreen.SetNegativeButton("CANCEL", delegate { }); } dlgToItemsScreen.Show(); }; imgAddStore.Click += (sender, e) => { var dlgAddNewStore = new AlertDialog.Builder(this); dlgAddNewStore.SetTitle("ADD A NEW STORE"); dlgAddNewStore.SetMessage("Please Enter a Name for a Store"); GridLayout grdNewStoreInfo = new GridLayout(this); grdNewStoreInfo.RowCount = 4; grdNewStoreInfo.ColumnCount = 1; EditText edtNewStoreName = new EditText(this); edtNewStoreName.SetWidth(600); grdNewStoreInfo.AddView(edtNewStoreName); //dlgAddNewStore.SetView(edtNewStoreName); TextView tvStoreURL = new TextView(this); tvStoreURL.SetTextColor(Android.Graphics.Color.White); tvStoreURL.Text = "Store URL (web address if known, otherwise we'll search):"; grdNewStoreInfo.AddView(tvStoreURL); // dlgAddNewStore.SetView(tvStoreURL); EditText edtStoreURL = new EditText(this); edtStoreURL.SetWidth(600); grdNewStoreInfo.AddView(edtStoreURL); // dlgAddNewStore.SetView(edtStoreURL); dlgAddNewStore.SetView(grdNewStoreInfo); dlgAddNewStore.SetPositiveButton("OK", delegate { string strNewStoreName = edtNewStoreName.Text; string strNewStoreURL = edtStoreURL.Text; var reqScanStores = new ScanRequest { TableName = "RetailStores" }; var respScanStores = dynDBClient.ScanAsync(reqScanStores); int iStoreCount = respScanStores.Result.Count; Table tblTheStores = Table.LoadTable(dynDBClient, "RetailStores"); Document docNewStore = new Document(); docNewStore["StoreID"] = iStoreCount.ToString(); docNewStore["StoreName"] = strNewStoreName; if (strNewStoreURL != "") { docNewStore["StoreURL"] = string.Concat("www.", strNewStoreName, ".com"); } tblTheStores.PutItemAsync(docNewStore); //this.listTheStores(dataStores,tvSelectedStoreName,grdStores); }); dlgAddNewStore.SetNegativeButton("CANCEL", delegate { }); dlgAddNewStore.Show(); }; }