コード例 #1
0
        /// <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>());
            }
        }
コード例 #2
0
        public async Task <List <Model.ObjectCode> > List(string parentObjectCodeId)
        {
            ListTablesResponse existingTables = await client.ListTablesAsync();

            if (!existingTables.TableNames.Contains(TABLE_NAME))
            {
                await SetupTable(client, TABLE_NAME, "CodeId");
            }

            try
            {
                List <ScanCondition> filter = new List <ScanCondition>()
                {
                    new ScanCondition("ParentId", ScanOperator.Equal, parentObjectCodeId.ToUpper())
                };
                AsyncSearch <Model.ObjectCode> scan = DDBContext.ScanAsync <Model.ObjectCode>(filter);

                List <Model.ObjectCode> documentList = new List <Model.ObjectCode>();
                do
                {
                    documentList.AddRange(await scan.GetNextSetAsync());
                } while (!scan.IsDone);

                return(documentList);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error listing object codes: " + ex.Message);
            }
            return(null);
        }
コード例 #3
0
ファイル: ValuesController.cs プロジェクト: lreb/aws-dynamodb
        public async Task <IActionResult> Get(string firstName, string lastName, string secondLastName, string curp)
        {
            var credentials = new BasicAWSCredentials(AWSAccessKeyId, AWSSecretAccessKey);
            var client      = new AmazonDynamoDBClient(credentials, RegionEndpoint.USWest2);

            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("FirstName", ScanOperator.Equal, firstName);
            scanFilter.AddCondition("LastName", ScanOperator.Equal, lastName);
            scanFilter.AddCondition("SecondLastName", ScanOperator.Equal, secondLastName);
            scanFilter.AddCondition("CURP", ScanOperator.Equal, curp);
            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));
        }
コード例 #4
0
        /// <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}");
            }
        }
コード例 #5
0
        public async Task <IEnumerable <BetsStat> > GetBetsStats()
        {
            AsyncSearch <BetsStat> search = context.ScanAsync <BetsStat>(Enumerable.Empty <ScanCondition>(), null);
            List <BetsStat>        result = await search.GetRemainingAsync();

            return(result);
        }
コード例 #6
0
        public async Task <IActionResult> GetAsync()
        {
            try
            {   // COGNITO SERVICE
                //AWSCredentials credentials = new CognitoAWSCredentials(cognitoID,RegionEndpoint.USEast1);
                //var client = new AmazonDynamoDBClient(credentials,RegionEndpoint.USEast1);

                // IAM SERVICE - Local
                //var credentials = new BasicAWSCredentials(AWSAccessKeyId, AWSSecretAccessKey);
                //var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);

                // This approach works when you are depending on a role
                var client = new AmazonDynamoDBClient(RegionEndpoint.USEast1);

                ScanFilter          scanFilter = new ScanFilter();
                ScanOperationConfig soc        = new ScanOperationConfig()
                {
                    Filter = scanFilter
                };
                DynamoDBContext    context      = new DynamoDBContext(client);
                AsyncSearch <lreb> search       = context.FromScanAsync <lreb>(soc, null);
                List <lreb>        documentList = new List <lreb>();
                do
                {
                    documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
                } while (!search.IsDone);

                return(Ok(documentList));
            }
            catch (Exception e)
            {
                return(StatusCode(500, e));
            }
        }
コード例 #7
0
        /// <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}");
            }
        }
コード例 #8
0
        /// <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>());
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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);
        }
コード例 #12
0
        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);
        }
コード例 #13
0
        /// <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());
        }
コード例 #14
0
        /// <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());
        }
コード例 #15
0
        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);
        }
コード例 #16
0
        /// <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);
        }
コード例 #17
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var searchOptions = new AsyncSearchOptions <List <DataMap> >(SearchAsync, ReloadData);

            _asyncSearch = new AsyncSearch <List <DataMap> >(View, searchOptions);

            tableView.Source = new TableSource(this);

            Title = _field.Label;
            AddSearchBar();
        }
コード例 #18
0
ファイル: ControllerBase.cs プロジェクト: csaam/thebreeze
        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);
        }
コード例 #19
0
        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());
        }
コード例 #20
0
        /// <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);
        }
コード例 #21
0
        /// <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());
        }
コード例 #22
0
        /// <summary>
        /// Configures an async Query operation against DynamoDB, finding items that match the specified hash primary key.
        /// </summary>
        /// <param name="hashKeyValue">Hash key of the items to query.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="take">The number of items to take.</param>
        /// <param name="queryFilter">Query filter for the Query operation operation.</param>
        /// <returns>The async task.</returns>
        private async Task <List <T> > QueryAsyncEx(object hashKeyValue, CancellationToken cancellationToken, int take = 100, List <ScanCondition> queryFilter = null)
        {
            List <T>        items        = new List <T>();
            AsyncSearch <T> result       = null;
            bool            foundEnought = false;

            // Add the filter.
            if (queryFilter != null)
            {
                // Add the query filter.
                DynamoDBOperationConfig operationConfig = new DynamoDBOperationConfig();
                operationConfig.QueryFilter = queryFilter;
                result = _context.QueryAsync <T>(hashKeyValue, operationConfig);
            }
            else
            {
                // Set the query.
                result = _context.QueryAsync <T>(hashKeyValue);
            }

            do
            {
                // Get the set of results.
                List <T> data = await result.GetNextSetAsync(cancellationToken);

                foreach (T entity in data)
                {
                    // Add the item found.
                    items.Add(entity);

                    // If we have enought.
                    if (items.Count >= take)
                    {
                        break;
                    }
                }

                // No more data.
                foundEnought = result.IsDone;

                // If we have enought.
                if (items.Count >= take)
                {
                    break;
                }
            }while (!foundEnought);

            // Return the list.
            return(items);
        }
コード例 #23
0
        public async Task <List <MediaItem> > LoadByUniqueNameAsync(Guid accountId, string uniqueName, bool decending)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                var config = new DynamoDBContextConfig {
                    TableNamePrefix = _tablePrefix
                };
                var context = new DynamoDBContext(_client, config);

                var operationConfig = new DynamoDBOperationConfig
                {
                    IndexName           = "UniqueMediaKey-DateAdded-index",
                    TableNamePrefix     = _tablePrefix,
                    ConditionalOperator = ConditionalOperatorValues.And,
                    OverrideTableName   = TableName,
                    BackwardQuery       = decending
                };

                // Pagination doesn't work to well at present (or at-least not start/limit type for Dynamo).
                // Pagination needs to use datetime range.

                var hashKeyValue            = string.Format("{0}-{1}", accountId, uniqueName.ToLower());
                var operatorType            = QueryOperator.Between;
                IEnumerable <object> values = new List <object>
                {
                    DateTime.MinValue,
                    DateTime.UtcNow,
                };

                AsyncSearch <MediaItem> asyncSearch = context.QueryAsync <MediaItem>(hashKeyValue, operatorType, values, operationConfig);

                List <MediaItem> items = await asyncSearch.GetNextSetAsync();

                // Assume one batch of query items is enough.
                // really needs to be paginated on date range.
                return(items.ToList());
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception loading media items");
                throw;
            }
            finally
            {
                stopwatch.Stop();
                Logger.LogMessage("LoadByUniqueNameAsync took: {0}ms", stopwatch.ElapsedMilliseconds);
            }
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        public async Task <List <MediaItem> > LoadByUserAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                var config = new DynamoDBContextConfig {
                    TableNamePrefix = _tablePrefix
                };
                var context = new DynamoDBContext(_client, config);

                //QueryFilter filter = new QueryFilter();
                //filter.AddCondition("UserId", QueryOperator.Equal, userId);

                var operationConfig = new DynamoDBOperationConfig
                {
                    IndexName           = "UserId-DateAdded-index",
                    TableNamePrefix     = _tablePrefix,
                    ConditionalOperator = ConditionalOperatorValues.And,
                    OverrideTableName   = TableName,
                    BackwardQuery       = true,
                };

                var hashKeyValue            = userId;
                var operatorType            = QueryOperator.Between;
                IEnumerable <object> values = new List <object> {
                    startDate, endDate
                };
                AsyncSearch <MediaItem> asyncSearch = context.QueryAsync <MediaItem>(hashKeyValue, operatorType, values, operationConfig);

                List <MediaItem> items = await asyncSearch.GetNextSetAsync();

                Logger.LogMessage("LoadByUserAsync loaded {0} items", items.Count);

                return(items);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception loading media items (LoadByUserAsync)");
                throw;
            }
            finally
            {
                stopwatch.Stop();
                Logger.LogMessage("LoadByUserAsync took: {0} ms", stopwatch.ElapsedMilliseconds);
            }
        }
コード例 #26
0
        /// <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>());
            }
        }
コード例 #27
0
        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.");
            }
        }
コード例 #28
0
        public async Task <IEnumerable <Expense> > GetExpenses()
        {
            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("Id", ScanOperator.NotEqual, 0);

            ScanOperationConfig soc = new ScanOperationConfig()
            {
                Filter = scanFilter
            };
            AsyncSearch <Expense> search       = context.FromScanAsync <Expense>(soc, null);
            List <Expense>        documentList = new List <Expense>();

            do
            {
                documentList = await search.GetNextSetAsync(default(System.Threading.CancellationToken));
            } while (!search.IsDone);

            return(documentList);
        }
コード例 #29
0
        public async Task <List <Coupon> > Get()
        {
            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);
        }
コード例 #30
0
ファイル: ListController.cs プロジェクト: lhrolim/softwrench
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var searchOptions = new AsyncSearchOptions <List <DataMap> >(SearchAsync, ReloadData);

            _asyncSearch = new AsyncSearch <List <DataMap> >(View, searchOptions);

            AddBorders();
            AddNavigationItems();
            AddSearchBar();
            SwitchOrientation(InterfaceOrientation);

            // TODO: this null check should be removed. If
            // metadata is null, Reload should not called
            // in the first place.
            if (null != _applicationMetadata)
            {
                ReloadData();
            }
        }
コード例 #31
0
        /// <summary>
        /// Performs an asynchronous search using the query parameters specified.
        /// On completion the AsyncCallback specified as callback is notified.
        /// </summary>
        /// <param name="queryParameters">A Google.CustomSearch.QueryParameters that specifies the search to be performed.</param>
        /// <param name="callback">A System.AsyncCallback object that will be notified when the call completes.</param>
        /// <returns>Returns a System.IAsyncResult that can be used to monitor the status of the asynchronous call.</returns>
        public IAsyncResult SearchAsync(QueryParameters queryParameters, AsyncCallback callback)
        {
            AsyncSearch caller = new AsyncSearch(this.Search);

            // TODO: What should be passed as the state object? is the Filter.Label appropriate?
            return caller.BeginInvoke(queryParameters, callback, queryParameters.Filter.Label);
        }