static void Main()
        {
            var client = new AmazonDynamoDBClient();

            TestBatchWrite(client);
        }
Example #2
0
        private IAmazonDynamoDB GetClient(AuditEvent auditEvent)
        {
            var client = new AmazonDynamoDBClient();

            return(client);
        }
Example #3
0
        public async Task <APIGatewayProxyResponse> Handler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            var client = new AmazonDynamoDBClient();

            var scanRequest = new ScanRequest
            {
                TableName            = Environment.ExpandEnvironmentVariables("%TABLE_NAME%"),
                ProjectionExpression = "connectionId"
            };

            ScanResponse connections = null;

            try
            {
                connections = await client.ScanAsync(scanRequest);
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = e.Message,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            var data      = JObject.Parse(input.Body)["data"].ToString();
            var byteArray = Encoding.UTF8.GetBytes(data);

            var config = new AmazonApiGatewayManagementApiConfig
            {
                ServiceURL = $"https://{input.RequestContext.DomainName}/{input.RequestContext.Stage}"
            };

            var apiClient = new AmazonApiGatewayManagementApiClient(config);

            var connectionIds = connections.Items.Select(item => item["connectionId"].S).ToList();

            foreach (var connectionId in connectionIds)
            {
                var postData = new MemoryStream(byteArray);

                try
                {
                    var postToRequest = new PostToConnectionRequest
                    {
                        ConnectionId = connectionId,
                        Data         = postData
                    };

                    await apiClient.PostToConnectionAsync(postToRequest);
                }
                catch (GoneException)
                {
                    Console.WriteLine($"Found dead connection, deleting {connectionId}");

                    var attributes = new Dictionary <string, AttributeValue>();

                    attributes["connectionId"] = new AttributeValue {
                        S = connectionId
                    };

                    var deleteRequest = new DeleteItemRequest
                    {
                        TableName = Environment.ExpandEnvironmentVariables("%TABLE_NAME%"),
                        Key       = attributes
                    };

                    try
                    {
                        await client.DeleteItemAsync(deleteRequest);
                    }
                    catch (Exception e)
                    {
                        return(new APIGatewayProxyResponse
                        {
                            StatusCode = (int)HttpStatusCode.InternalServerError,
                            Body = e.Message,
                            Headers = new Dictionary <string, string> {
                                { "Content-Type", "text/plain" }
                            },
                        });
                    }
                }
                catch (Exception e)
                {
                    return(new APIGatewayProxyResponse
                    {
                        StatusCode = (int)HttpStatusCode.InternalServerError,
                        Body = e.Message,
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }
            }

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = "data sent",
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            });
        }
 private async Task CallUntilCompletionAsync(BatchWriteItemRequest request, Dictionary <string, Dictionary <Key, Document> > documentMap, AmazonDynamoDBClient client, CancellationToken cancellationToken)
 public TradeServiceDAL(string tableName)
 {
     this.client = new AmazonDynamoDBClient();
     this.table  = Table.LoadTable(this.client, tableName);
 }
Example #6
0
        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);
            }
        }
Example #7
0
 public GenericGet(AmazonDynamoDBClient amazonDynamoDBClient)
 {
     AmazonDynamoDBClient = amazonDynamoDBClient;
 }
        public static async void RetrieveMultipleItemsBatchGet(AmazonDynamoDBClient client)
        {
            var request = new BatchGetItemRequest
            {
                RequestItems = new Dictionary <string, KeysAndAttributes>()
                {
                    { _table1Name,
                      new KeysAndAttributes
                      {
                          Keys = new List <Dictionary <string, AttributeValue> >()
                          {
                              new Dictionary <string, AttributeValue>()
                              {
                                  { "Name", new AttributeValue {
                                    S = "Amazon DynamoDB"
                                } }
                              },
                              new Dictionary <string, AttributeValue>()
                              {
                                  { "Name", new AttributeValue {
                                    S = "Amazon S3"
                                } }
                              }
                          }
                      } },
                    {
                        _table2Name,
                        new KeysAndAttributes
                        {
                            Keys = new List <Dictionary <string, AttributeValue> >()
                            {
                                new Dictionary <string, AttributeValue>()
                                {
                                    { "ForumName", new AttributeValue {
                                          S = "Amazon DynamoDB"
                                      } },
                                    { "Subject", new AttributeValue {
                                          S = "DynamoDB Thread 1"
                                      } }
                                },
                                new Dictionary <string, AttributeValue>()
                                {
                                    { "ForumName", new AttributeValue {
                                          S = "Amazon DynamoDB"
                                      } },
                                    { "Subject", new AttributeValue {
                                          S = "DynamoDB Thread 2"
                                      } }
                                },
                                new Dictionary <string, AttributeValue>()
                                {
                                    { "ForumName", new AttributeValue {
                                          S = "Amazon S3"
                                      } },
                                    { "Subject", new AttributeValue {
                                          S = "S3 Thread 1"
                                      } }
                                }
                            }
                        }
                    }
                }
            };

            BatchGetItemResponse response;

            do
            {
                Console.WriteLine("Making request");
                response = await client.BatchGetItemAsync(request);

                // Check the response.
                var responses = response.Responses; // Attribute list in the response.

                foreach (var tableResponse in responses)
                {
                    var tableResults = tableResponse.Value;
                    Console.WriteLine("Items retrieved from table {0}", tableResponse.Key);
                    foreach (var item1 in tableResults)
                    {
                        PrintItem(item1);
                    }
                }

                // Any unprocessed keys? could happen if you exceed ProvisionedThroughput or some other error.
                Dictionary <string, KeysAndAttributes> unprocessedKeys = response.UnprocessedKeys;
                foreach (var unprocessedTableKeys in unprocessedKeys)
                {
                    // Print table name.
                    Console.WriteLine(unprocessedTableKeys.Key);
                    // Print unprocessed primary keys.
                    foreach (var key in unprocessedTableKeys.Value.Keys)
                    {
                        PrintItem(key);
                    }
                }

                request.RequestItems = unprocessedKeys;
            } while (response.UnprocessedKeys.Count > 0);
        }
Example #9
0
        public static async Task Main(string[] args)
        {
            var configfile = "app.config";
            var region     = string.Empty;
            var table      = string.Empty;
            var partition  = string.Empty;
            var sort       = string.Empty;

            // Get default Region and table from config file.
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile,
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;

                if ((region == string.Empty) || (table == string.Empty))
                {
                    Console.WriteLine($"You must specify a Region and Table value in {configfile}");
                    return;
                }
            }
            else
            {
                Console.WriteLine($"Could not find {configfile}");
                return;
            }

            // Get command line arguments for item to delete.
            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-p":
                    i++;
                    partition = args[i];
                    break;

                case "-s":
                    i++;
                    sort = args[i];
                    break;
                }

                i++;
            }

            if ((partition == string.Empty) || (sort == string.Empty))
            {
                Console.WriteLine("You must supply a partition key (-p KEY) and sort key (-s KEY)");
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            var resp = await RemoveItemAsync(client, table, partition, sort);

            if (resp.HttpStatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine($"Removed item from {table} table in {region} region");
            }
        }
Example #10
0
        /**
         * Find a valid link with the ID and type passed in.
         */
        internal static async Task <Link> FindValidLink(AmazonDynamoDBClient dbClient, string linkID, string type)
        {
            Debug.Untested();
            Debug.AssertString(linkID);
            Debug.AssertString(type);
            //??--Debug.AssertValid(Links);

            Link retVal     = null;
            var  linkDBItem = await IdentityServiceDataLayer.GetLinkDBItemById(dbClient, linkID);

            Debug.AssertValidOrNull(linkDBItem);
            if (linkDBItem != null)
            {
                // A link with the specified ID exists.
                Debug.Untested();
                Link link = IdentityServiceDataLayer.LinkFromDBItem(linkDBItem);
                Debug.AssertValid(link);
                if (link.Type == type)
                {
                    // Correct type
                    Debug.Untested();
                    if (link.Expires > DateTime.Now)
                    {
                        // Not expired
                        Debug.Untested();
                        if (!link.Revoked)
                        {
                            // Not revoked
                            Debug.Untested();
                            retVal = link;
                        }
                        else
                        {
                            // Revoked
                            Debug.Untested();
                        }
                    }
                    else
                    {
                        // Expired
                        Debug.Untested();
                    }
                }
                else
                {
                    // Wrong type
                    Debug.Untested();
                }
            }
            else
            {
                // Link not found
                Debug.Untested();
            }
            //??-- if (Links.ContainsKey(linkID)) {
            //     Debug.Tested();
            //     retVal = Links[linkID];
            //     Debug.AssertValid(retVal);
            //     if (retVal.Type != type) {
            //         Debug.Tested();
            //         retVal = null;
            //     } else if (retVal.Expires <= DateTime.Now) {
            //         Debug.Tested();
            //         retVal = null;
            //     } else if (retVal.Revoked) {
            //         Debug.Tested();
            //         retVal = null;
            //     } else {
            //         Debug.Tested();
            //     }
            // } else {
            //     Debug.Tested();
            // }
            return(retVal);
        }
        static void Main()
        {
            var client = new AmazonDynamoDBClient();

            RetrieveMultipleItemsBatchGet(client);
        }
Example #12
0
        /**
         * Get the ID of the logged in user from the access token.
         * If the access token has expired then treat it as not existing and return zero (i.e. invalid ID).
         */
        internal static async Task <string> UserIDFromAccessToken(AmazonDynamoDBClient dbClient, string accessTokenID)
        {
            Debug.Untested();
            Debug.AssertValidOrNull(accessTokenID);

            string retVal = Helper.INVALID_ID;

            if (!string.IsNullOrEmpty(accessTokenID))
            {
                Debug.Untested();
                var accessTokenDBItem = await IdentityServiceDataLayer.GetAccessTokenDBItemById(dbClient, accessTokenID);

                Debug.AssertValidOrNull(accessTokenDBItem);
                if (accessTokenDBItem != null)
                {
                    // An access token with the specified ID exists.
                    Debug.Untested();
                    AccessToken accessToken = IdentityServiceDataLayer.AccessTokenFromDBItem(accessTokenDBItem);
                    Debug.AssertValid(accessToken);
                    if (accessToken.Expires > DateTime.Now)
                    {
                        // The access token has not expired.
                        Debug.Untested();
                        Debug.AssertID(accessToken.UserID);
                        retVal = accessToken.UserID;
                    }
                    else
                    {
                        // The access token has expired.
                        Debug.Untested();
                    }
                }
                else
                {
                    // Access token not found.
                    Debug.Tested();
                }
            }
            else
            {
                // Invalid (empty or null) access token.
                Debug.Untested();
            }
            //??--     if (AccessTokens.ContainsKey(accessTokenID)) {
            //         Debug.Tested();
            //         AccessToken accessToken = AccessTokens[accessTokenID];
            //         Debug.AssertValid(accessToken);
            //         Debug.AssertValidOrNull(accessToken.User);
            //         if (accessToken.Expires > DateTime.Now) {
            //             // The access token has not expired.
            //             Debug.Tested();
            //             if (accessToken.User != null) {
            //                 // Access token associated with a user.
            //                 Debug.Tested();
            //                 Debug.AssertID(accessToken.User.ID);
            //                 retVal = accessToken.User.ID;
            //             } else {
            //                 // Access token not associated with a user.
            //                 Debug.Untested();
            //             }
            //         }
            //         else
            //         {
            //             // The access token has expired.
            //             Debug.Untested();
            //         }
            //     } else {
            //         // Access token not found.
            //         Debug.Tested();
            //     }
            // } else {
            //     // Invalid (empty or null) access token.
            //     Debug.Untested();
            // }
            return(retVal);
        }
Example #13
0
        /**
         * Setup the test users.
         */
        //??? internal static void SetupTestUsers() {
        //     Debug.Tested();

        //     int userNumber = 1;
        //     string userId = userNumber.ToString();

        //     // Add a super admin (with ID 1)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "Stuart",
        //         FamilyName = "Prestedge"
        //     });
        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_SUPER_ADMIN));
        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_ADMIN));
        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_CAN_LOCK_SYSTEM));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CREATE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UPDATE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_LOCK_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UNLOCK_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_PUBLISH_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_FREEZE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_GAME_CLOSE_DATE));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_GAME_DONATED_TO_CHARITY));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_DELETE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CREATE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UPDATE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_DATE));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_AMOUNT));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_AUTO_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_WINNING_NUMBER));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CLEAR_DRAW_WINNING_NUMBER));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_DELETE_DRAW));
        //     userId = (++userNumber).ToString();

        //     // Add an admin (all permissions, with ID 2)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "Admin"
        //     });
        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_ADMIN));
        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_CAN_LOCK_SYSTEM));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CREATE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UPDATE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_LOCK_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UNLOCK_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_PUBLISH_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_FREEZE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_GAME_CLOSE_DATE));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_GAME_DONATED_TO_CHARITY));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_DELETE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CREATE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UPDATE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_DATE));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_AMOUNT));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_AUTO_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_SET_DRAW_WINNING_NUMBER));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CLEAR_DRAW_WINNING_NUMBER));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_DELETE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_BUY_TICKETS));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_OFFER_TICKET));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_REVOKE_TICKET));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_ACCEPT_TICKET));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_REJECT_TICKET));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_RESERVE_TICKET));
        //     Permissions.Add(new Tuple<string, string>(userId, TicketingServiceLogicLayer.PERMISSION_CAN_GET_TICKET_AUDITS));
        //     userId = (++userNumber).ToString();

        //     // Add an admin (no permissions, with ID 3)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "Admin (no permissions)"
        //     });
        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_ADMIN));
        //     userId = (++userNumber).ToString();

        //     // Add a user (with ID 4)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "User"
        //     });
        //     userId = (++userNumber).ToString();

        //     // Add a second user (with ID 5)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "User 2"
        //     });
        //     userId = (++userNumber).ToString();

        //     // Add a editor user (with ID 6)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "User 6"
        //     });

        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_ADMIN));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CREATE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UPDATE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_LOCK_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_DELETE_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_CREATE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UPDATE_DRAW));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_DELETE_DRAW));
        //     userId = (++userNumber).ToString();

        //     // Add a publisher user (with ID 7)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "User 2"
        //     });

        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_ADMIN));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_PUBLISH_GAME));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_UNLOCK_GAME));
        //     userId = (++userNumber).ToString();

        //     // Add a freezer user (with ID 7)
        //     AddUserCreatingSyndicate(new User() {
        //         ID = userId,
        //         EmailAddress = "*****@*****.**",
        //         PasswordHash = Helper.Hash("Passw0rd"),
        //         GivenName = "BDD",
        //         FamilyName = "User 2"
        //     });

        //     Permissions.Add(new Tuple<string, string>(userId, PERMISSION_IS_ADMIN));
        //     Permissions.Add(new Tuple<string, string>(userId, GameServiceLogicLayer.PERMISSION_CAN_FREEZE_GAME));
        //     userId = (++userNumber).ToString();
        // }

        /**
         * Find a user by ID.
         */
        internal static async Task <User> FindUserByID(AmazonDynamoDBClient dbClient, string userId, bool ignoreClosed = false)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);

            User retVal     = null;
            var  userDBItem = await IdentityServiceDataLayer.GetUserDBItemById(dbClient, userId);

            Debug.AssertValidOrNull(userDBItem);
            if (userDBItem != null)
            {
                // A user with the specified ID exists.
                Debug.Untested();
                if (IdentityServiceDataLayer.GetUserDBItemDeleted(userDBItem) == null)
                {
                    // The user is not deleted
                    if (!ignoreClosed || (IdentityServiceDataLayer.GetUserDBItemClosed(userDBItem) == null))
                    {
                        // Not ignoring closed or the user is not closed
                        retVal = IdentityServiceDataLayer.UserFromDBItem(userDBItem);
                        Debug.AssertValid(retVal);
                    }
                    else
                    {
                        // The user is closed and we are ignoring closed users.
                        Debug.Untested();
                    }
                }
                else
                {
                    // The user is deleted
                    Debug.Untested();
                }
            }
            else
            {
                // A user with the specified ID does not exist.
                Debug.Untested();
            }
            //??-- foreach (User user in Users) {
            //     Debug.Tested();
            //     Debug.AssertValid(user);
            //     if (user.Deleted == null) {
            //         // The user record is not deleted
            //         Debug.Tested();
            //         if (user.ID == userId) {
            //             // Found user with specified ID.
            //             Debug.Tested();
            //             if (user.Closed == null) {
            //                 // The user account is not closed so return it.
            //                 Debug.Tested();
            //                 retVal = user;
            //             } else if (!ignoreClosed) {
            //                 // The user account is closed but, because we are not ignoring closed accounts, return it.
            //                 Debug.Untested();
            //                 retVal = user;
            //             } else {
            //                 // Ignore the closed user account (i.e. return null).
            //                 Debug.Tested();
            //             }
            //             break;
            //         } else {
            //             // User is not the one with the specified ID.
            //             Debug.Tested();
            //         }
            //     } else {
            //         // The user record has been soft deleted so ignore it.
            //         Debug.Untested();
            //     }
            // }
            return(retVal);
        }
Example #14
0
        static Program()
        {
            var dbCredentials = new BasicAWSCredentials(dbAccessKey, dbSecretKey);

            dbClient = new AmazonDynamoDBClient(dbCredentials, RegionEndpoint.EUCentral1);
        }
Example #15
0
 public MobRepository()
 {
     _client  = AmazonDynamoDBClientSingleton.Instance;
     _context = new DynamoDBContext(_client);
 }
Example #16
0
 private static void CleanUp()
 {
     _client = null;
     _describeTableResponse = null;
     _table = null;
 }
Example #17
0
        // Receiving a message
        public void ReceviveMessage(string endpoint, string queuename)
        {
            //var sqs = AWSClientFactory.CreateAmazonSQSClient();
            AmazonSQSConfig amazonSqsConfig = new AmazonSQSConfig {
                ServiceURL = endpoint
            };
            AmazonSQSClient sqs = new AmazonSQSClient(amazonSqsConfig);


            var receiveMessageRequest = new ReceiveMessageRequest
            {
                AttributeNames = new List <string>()
                {
                    "All"
                },
                MaxNumberOfMessages = 10,
                QueueUrl            = endpoint + Program.MyAccountNumber + Program.Queuename,
                VisibilityTimeout   = (int)TimeSpan.FromMinutes(2).TotalSeconds,
                WaitTimeSeconds     = (int)TimeSpan.FromSeconds(5).TotalSeconds
            };

            // var receiveMessageRequest = new ReceiveMessageRequest { QueueUrl = USwest2Url };
            var receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest);

            if (receiveMessageResponse.Messages.Count > 0)
            {
                Console.WriteLine("Printing received message from \n" + endpoint + Program.MyAccountNumber + Program.Queuename);
                foreach (var message in receiveMessageResponse.Messages)
                {
                    //                    if (!string.IsNullOrEmpty(message.MessageId))
                    //                    {
                    //                        Console.WriteLine("    MessageId: {0}", message.MessageId);
                    //                    }
                    //                    if (!string.IsNullOrEmpty(message.ReceiptHandle))
                    //                    {
                    //                        Console.WriteLine("    ReceiptHandle: {0}", message.ReceiptHandle);
                    //                    }
                    //                    if (!string.IsNullOrEmpty(message.MD5OfBody))
                    //                    {
                    //                        Console.WriteLine("    MD5OfBody: {0}", message.MD5OfBody);
                    //                    }
                    //                    if (!string.IsNullOrEmpty(message.Body))
                    //                    {
                    //                        Console.WriteLine("    Body: {0}", message.Body);
                    //                    }


                    if (message.Body.Count() > 5)
                    {
                        //Console.WriteLine("Setting up DynamoDB client");

                        AmazonDynamoDBConfig config = new AmazonDynamoDBConfig();
                        config.ServiceURL = Program.DynamoDbUSwest2Endpoint;
                        var client = new AmazonDynamoDBClient(config);


                        TableOperations.PutItem(client, s, endpoint, message.MessageId);
                        // TableOperations.PutItem2(5,client, s, endpoint);
                        s[0]++;
                    }
                    else
                    {
                        Console.WriteLine("nothing sent ");
                    }

                    //
                    //                    foreach (string attributeKey in message.Attributes.Keys)
                    //                    {
                    //                        Console.WriteLine("  Attribute");
                    //                        Console.WriteLine("    Name: {0}", attributeKey);
                    //                        var value = message.Attributes[attributeKey];
                    //                        Console.WriteLine("    Value: {0}", string.IsNullOrEmpty(value) ? "(no value)" : value);
                    //                    }

                    // var messageRecieptHandle = receiveMessageResponse.Messages[0].ReceiptHandle;
//                                        var messageRecieptHandle = message.ReceiptHandle;
//
//                                        //Deleting a message
//                                        DateTime t = DateTime.Now;
//                                        Console.WriteLine("Deleting the message from queue.\n"+t);
//                                        var deleteRequest = new DeleteMessageRequest
//                                        {
//                                           QueueUrl = endpoint +Program.MyAccountNumber+ Program.Queuename,
//                                            ReceiptHandle = messageRecieptHandle
//                                        };
//                                        sqs.DeleteMessage(deleteRequest);
                }
            }
            else
            {
                Console.WriteLine("No messages received.");
            }
        }
Example #18
0
        public static bool CreateClient()
        {
            if (_useDynamoDBLocal)
            {
                //parse ip address and port
                int    i         = _localServiceURL.Contains("://") ? _localServiceURL.IndexOf("://") : -3;
                string ipAddress = _localServiceURL.Substring(i + 3);

                i = ipAddress.Contains(":") ? ipAddress.IndexOf(":") : -1;
                if (i == -1)
                {
                    ShowError("ERROR: Port not found. Please specify a port");
                    return(false);
                }
                string portText = ipAddress.Substring(i + 1);
                ipAddress = ipAddress.Substring(0, i);
                int port = 0;
                if (!int.TryParse(portText, out port))
                {
                    ShowError("ERROR: Port is not a number. Please specify a valid port");
                    return(false);
                }

                // First, check to see whether anyone is listening on the DynamoDB local port
                // (by default, this is port 8000, so if you are using a different port, modify this accordingly)
                bool localFound = false;
                try
                {
                    using (var tcp_client = new TcpClient())
                    {
                        var result = tcp_client.BeginConnect(ipAddress, port, null, null);
                        localFound = result.AsyncWaitHandle.WaitOne(3000); // Wait 3 seconds
                        tcp_client.EndConnect(result);
                    }
                }
                catch
                {
                    localFound = false;
                }
                if (!localFound)
                {
                    ShowError("ERROR: DynamoDB Local does not appear to have been started. Checked port " + port);
                    return(false);
                }

                CredentialProfileStoreChain chain = new CredentialProfileStoreChain();
                AWSCredentials credentials;

                if (!chain.TryGetAWSCredentials(_awsProfile, out credentials))
                {
                    ShowError("Profile {0} not found", _awsProfile);
                    return(false);
                }

                RegionEndpoint region = RegionEndpoint.GetBySystemName(_awsRegion);

                if (region == null)
                {
                    ShowError("Region {0} not found", _awsRegion);
                    return(false);
                }

                // If DynamoDB-Local does seem to be running, so create a client
                ShowInfo("Setting up a DynamoDB-Local client (DynamoDB Local seems to be running)");
                AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
                ddbConfig.ServiceURL = _localServiceURL;

                try
                {
                    //_client = new AmazonDynamoDBClient(ddbConfig);
                    _client = new AmazonDynamoDBClient(credentials, ddbConfig);
                }
                catch (Exception ex)
                {
                    ShowError("FAILED to create a DynamoDBLocal client; " + ex.Message);
                    return(false);
                }
            }

            else
            {
                CredentialProfileStoreChain chain = new CredentialProfileStoreChain();
                AWSCredentials credentials;

                if (!chain.TryGetAWSCredentials(_awsProfile, out credentials))
                {
                    ShowError("Profile {0} not found", _awsProfile);
                    return(false);
                }

                RegionEndpoint region = RegionEndpoint.GetBySystemName(_awsRegion);

                if (region == null)
                {
                    ShowError("Region {0} not found", _awsRegion);
                    return(false);
                }

                //If MFA is enabled on this probile, ask for an access code
                AssumeRoleAWSCredentials assumeCredentials = credentials as AssumeRoleAWSCredentials;
                if (assumeCredentials != null && !string.IsNullOrWhiteSpace(assumeCredentials.Options.MfaSerialNumber))
                {
                    assumeCredentials.Options.MfaTokenCodeCallback = () =>
                    {
                        Console.WriteLine("Enter MFA code: ");
                        return(Console.ReadLine());
                    };
                }

                try
                {
                    ShowInfo("Connecting to DynamoDB with profile {0} in region {1}", _awsProfile, _awsRegion);
                    _client = new AmazonDynamoDBClient(credentials, region);
                }
                catch (Exception ex)
                {
                    ShowError("     FAILED to create a DynamoDB client; " + ex.Message);
                    return(false);
                }
            }
            return(true);
        }
Example #19
0
        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();
            };
        }
Example #20
0
        /// <summary>
        /// Example that writes to a DynamoDb more than one item in one call.
        /// </summary>
        /// <returns></returns>
        public static async Task BatchWriteExampleAsync()
        {
            //Create Client
            var client = new AmazonDynamoDBClient(RegionEndpoint.USWest2);

            //Definition of the first item to put on a table
            var putFirstItem = new PutRequest(new Dictionary <string, AttributeValue>
            {
                { "pk", new AttributeValue("*****@*****.**") },
                { "sk", new AttributeValue("metadata") },
                { "attribute1", new AttributeValue("Attribute1 value") }
                //Add other attributes as you need
            }
                                              );
            //Definition of the second item to put on a table
            var putSecondItem = new PutRequest(new Dictionary <string, AttributeValue>
            {
                { "pk", new AttributeValue("*****@*****.**") },
                { "sk", new AttributeValue("metadata") },
                { "attribute1", new AttributeValue("Attribute1 value") }
                //Add other attributes as you need
            }
                                               );
            //Definition of an item to delete
            var deleteItem = new DeleteRequest(new Dictionary <string, AttributeValue>
            {
                { "pk", new AttributeValue("*****@*****.**") },
                { "sk", new AttributeValue("metadata") },
            }
                                               );

            //Request that group all the previous Put & Delete actions
            var writeRequest = new BatchWriteItemRequest
            {
                RequestItems = new Dictionary <string, List <WriteRequest> >
                {
                    {
                        //Name of the table
                        "RetailDatabase",
                        new List <WriteRequest>()
                        {
                            new WriteRequest(putFirstItem),
                            new WriteRequest(putSecondItem),
                            new WriteRequest(deleteItem)
                        }
                    },//You can execute other collections of requests on other tables at the same time
                    {
                        //Name of the table
                        "RetailDatabase2",
                        new List <WriteRequest>()
                        {
                            new WriteRequest(putFirstItem),
                            new WriteRequest(putSecondItem),
                            new WriteRequest(deleteItem)
                        }
                    }
                }
            };

            try
            {
                //Execution of the request
                var responseWrite = await client.BatchWriteItemAsync(writeRequest);

                Console.WriteLine($"Status {responseWrite.HttpStatusCode}");
                Console.WriteLine($"Number of items not processed that you need to try again:{responseWrite.UnprocessedItems}");
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
        }
Example #21
0
 private void CallUntilCompletion(BatchWriteItemRequest request, Dictionary <string, Dictionary <Key, Document> > documentMap, AmazonDynamoDBClient client)
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task FunctionHandler(S3Event input, ILambdaContext context)
        {
            // Initialize the Amazon Cognito credentials provider
            CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                "us-east-1:6d711ae9-1084-4a71-9ef6-7551ca74ad0b", // Identity pool ID
                RegionEndpoint.USEast1                            // Region
                );

            dynamoDbClient = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);
            Table customersTbl = Table.LoadTable(dynamoDbClient, "Customer");


            AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
            IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USEast2);

            //Debug.WriteLine("Creating collection: " + FACE_COLLECTION_ID);
            //CreateCollectionRequest createCollectionRequest = new CreateCollectionRequest()
            //{
            //    CollectionId = FACE_COLLECTION_ID
            //};

            //CreateCollectionResponse createCollectionResponse = rekognitionClient.CreateCollectionAsync(createCollectionRequest).Result;
            //Debug.WriteLine("CollectionArn : " + createCollectionResponse.CollectionArn);
            //Debug.WriteLine("Status code : " + createCollectionResponse.StatusCode);


            foreach (var record in input.Records)
            {
                //if(!SupportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key)))
                //{
                //    Debug.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type");
                //    continue;
                //}

                Image image = new Image()
                {
                    S3Object = new Amazon.Rekognition.Model.S3Object
                    {
                        Bucket = record.S3.Bucket.Name,
                        Name   = record.S3.Object.Key
                    }
                };

                GetObjectTaggingResponse taggingResponse = s3Client.GetObjectTaggingAsync(
                    new GetObjectTaggingRequest
                {
                    BucketName = record.S3.Bucket.Name,
                    Key        = record.S3.Object.Key
                }
                    ).Result;

                Tag customerID = taggingResponse.Tagging[0];//TODO: HARDCODING!!


                IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
                {
                    Image               = image,
                    CollectionId        = FACE_COLLECTION_ID,
                    ExternalImageId     = record.S3.Object.Key,
                    DetectionAttributes = new List <String>()
                    {
                        "ALL"
                    }
                };

                IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFacesAsync(indexFacesRequest).Result;

                Debug.WriteLine(record.S3.Object.Key + " added");
                foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
                {
                    Debug.WriteLine("Face detected: Faceid is " + faceRecord.Face.FaceId);

                    Console.WriteLine("\nAfter Indexing, Updating FaceID of the Customer....");
                    string partitionKey = customerID.Value;

                    var customer = new Document();
                    customer["Id"] = Int32.Parse(partitionKey);
                    // List of attribute updates.
                    // The following replaces the existing authors list.
                    customer["FaceId"] = faceRecord.Face.FaceId;

                    // Optional parameters.
                    UpdateItemOperationConfig config = new UpdateItemOperationConfig
                    {
                        // Get updated item in response.
                        ReturnValues = ReturnValues.AllNewAttributes
                    };
                    Document updatedCustomer = customersTbl.UpdateItemAsync(customer, config).Result;
                    Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
                    PrintDocument(updatedCustomer);
                }
            }
            return;
        }
        private static AmazonDynamoDBClient CreateClient()
        {
            var client = new AmazonDynamoDBClient(region);

            return(client);
        }
Example #24
0
        internal S3ClientCache(AmazonDynamoDBClient ddbClient)
        {
            this.ddbClient = ddbClient;

            this.clientsByRegion = new Dictionary <string, ICoreAmazonS3>(StringComparer.OrdinalIgnoreCase);
        }
        //Function Handler is an entry point to start execution of Lambda Function.
        //It takes Input Data as First Parameter and ObjectContext as Second
        public async Task FunctionHandler(UserLocationModel locationModel, ILambdaContext context)
        {
            //Write Log to Cloud Watch using Console.WriteLline.
            Console.WriteLine("Execution started for function -  {0} at {1}",
                              context.FunctionName, DateTime.Now);

            // Create  dynamodb client
            var dynamoDbClient = new AmazonDynamoDBClient(
                new AmazonDynamoDBConfig
            {
                //ServiceURL = _serviceUrl,
                RegionEndpoint = RegionEndpoint.USEast1,
            });

            // Update location of user
            LambdaLogger.Log("Update location for record");

            locationModel.Username = locationModel.Username.ToLowerInvariant();
            locationModel.Room     = locationModel.Room.ToLowerInvariant();

            if (!locationModel.IsInOffice)
            {
                locationModel.Room = "out";
            }
            else if (string.IsNullOrWhiteSpace(locationModel.Room))
            {
                throw new ArgumentNullException("room");
            }

            await dynamoDbClient.UpdateItemAsync(new UpdateItemRequest
            {
                Key = new Dictionary <string, AttributeValue>
                {
                    { "Username", new AttributeValue(locationModel.Username) }
                },
                TableName                 = _tableName,
                UpdateExpression          = "SET IsInOffice = :o, Room = :r, RoomHistory = list_append(if_not_exists(RoomHistory, :empty_list), :room_history_record)" + (locationModel.IsInOffice ? ", LastTimeInOffice = :lt" : string.Empty),
                ConditionExpression       = "Room <> :r",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":o", new AttributeValue {
                          BOOL = locationModel.IsInOffice
                      } },
                    { ":r", new AttributeValue {
                          S = locationModel.Room
                      } },
                    { ":room_history_record", new AttributeValue {
                          L = new List <AttributeValue> {
                              new AttributeValue {
                                  S = locationModel.Room
                              }
                          }
                      } },
                    { ":empty_list", new AttributeValue {
                          IsLSet = true
                      } },
                    { ":lt", new AttributeValue {
                          S = DateTime.Now.ToShortDateString()
                      } }
                }
            });

            //Write Log to cloud watch using context.Logger.Log Method
            context.Logger.Log(string.Format("Finished execution for function -- {0} at {1}",
                                             context.FunctionName, DateTime.Now));
        }
 public DynamoDbService()
 {
     _dynamoDbClient  = new AmazonDynamoDBClient(RegionEndpoint.USWest2);
     _dynamoDbContext = new DynamoDBContext(_dynamoDbClient);
 }
Example #27
0
 public DynamoContext(Connection conn)
 {
     database = new AmazonDynamoDBClient(conn.Key, conn.EndPoint, conn.UserDefined.GetAmazonRegion());
     context  = new DynamoDBContext(database);
 }
 public DynamoDbService(AmazonDynamoDBClient amazonDynamoDbClient, DynamoDBContext dynamoDbContext)
 {
     _dynamoDbClient  = amazonDynamoDbClient;
     _dynamoDbContext = dynamoDbContext;
 }
 public SasDynamoContext(SasDynamoDbConfig config, AmazonDynamoDBClient client)
 {
     _config = config;
     _client = client;
 }
 public PutAccountHandler()
 {
     _client  = new AmazonDynamoDBClient(Amazon.RegionEndpoint.USEast1);
     _context = new DynamoDBContext(_client);
 }
        internal S3ClientCache(AmazonDynamoDBClient ddbClient)
        {
            this.ddbClient = ddbClient;

            this.clientsByRegion = new Dictionary<string, ICoreAmazonS3>(StringComparer.OrdinalIgnoreCase);
        }
Example #32
0
 public DynamoDbClient()
     : base()
 {
     var config = new AmazonDynamoDBConfig();
     client = new AmazonDynamoDBClient(config);
 }