public static void RunDataModelSample()
        {
            Console.WriteLine("Creating the context object");
            DynamoDBContext context = new DynamoDBContext(client);

            Console.WriteLine("Creating actors");
            Actor christianBale = new Actor
            {
                Name = "Christian Bale",
                Bio = "Christian Charles Philip Bale is an excellent horseman and an avid reader.",
                BirthDate = new DateTime(1974, 1, 30),
                Address = new Address
                {
                    City = "Los Angeles",
                    Country = "USA"
                },
                HeightInMeters = 1.83f
            };
            Actor michaelCaine = new Actor
            {
                Name = "Michael Caine",
                Bio = "Maurice Joseph Micklewhite is an English actor, better known as Michael Caine",
                BirthDate = new DateTime(1933, 3, 14),
                Address = new Address
                {
                    City = "London",
                    Country = "England"
                },
                HeightInMeters = 1.88f
            };

            Console.WriteLine("Creating movie");
            Movie darkKnight = new Movie
            {
                Title = "The Dark Knight",
                ReleaseDate = new DateTime(2008, 7, 18),
                Genres = new List<string> { "Action", "Crime", "Drama" },
                ActorNames = new List<string>
                {
                    christianBale.Name,
                    michaelCaine.Name
                }
            };

            Console.WriteLine("Saving actors and movie");
            context.Save<Actor>(michaelCaine);
            context.Save<Actor>(christianBale);
            context.Save<Movie>(darkKnight);

            Console.WriteLine("Creating and saving new actor");
            Actor maggieGyllenhaal = new Actor
            {
                Name = "Maggie Gyllenhaal",
                BirthDate = new DateTime(1977, 11, 16),
                Bio = "Maggie Gyllenhaal studied briefly at the Royal Academy of Dramatic Arts in London.",
                Address = new Address
                {
                    City = "New York City",
                    Country = "USA"
                },
                HeightInMeters = 1.75f
            };
            context.Save<Actor>(maggieGyllenhaal);

            Console.WriteLine();
            Console.WriteLine("Loading existing movie");
            Movie existingMovie = context.Load<Movie>("The Dark Knight", new DateTime(2008, 7, 18));
            Console.WriteLine(existingMovie.ToString());

            Console.WriteLine();
            Console.WriteLine("Loading nonexistent movie");
            Movie nonexistentMovie = context.Load<Movie>("The Dark Knight", new DateTime(2008, 7, 19));
            Console.WriteLine("Movie is null : " + (nonexistentMovie == null));

            Console.WriteLine("Updating movie and saving");
            existingMovie.ActorNames.Add(maggieGyllenhaal.Name);
            existingMovie.Genres.Add("Thriller");
            context.Save<Movie>(existingMovie);

            Console.WriteLine("Adding movie with same hash key but different range key");
            Movie darkKnight89 = new Movie
            {
                Title = "The Dark Knight",
                Genres = new List<string> { "Drama" },
                ReleaseDate = new DateTime(1989, 2, 23),
                ActorNames = new List<string>
                {
                    "Juan Diego",
                    "Fernando Guillén",
                    "Manuel de Blas"
                }
            };
            context.Save<Movie>(darkKnight89);

            IEnumerable<Movie> movieQueryResults;

            Console.WriteLine();
            Console.WriteLine("Running query 1, expecting 1 result");
            movieQueryResults = context.Query<Movie>("The Dark Knight", QueryOperator.GreaterThan, new DateTime(1995, 1, 1));
            foreach (var result in movieQueryResults)
                Console.WriteLine(result.ToString());

            Console.WriteLine();
            Console.WriteLine("Running query 2, expecting 2 results");
            movieQueryResults = context.Query<Movie>("The Dark Knight", QueryOperator.Between, new DateTime(1970, 1, 1), new DateTime(2011, 1, 1));
            foreach (var result in movieQueryResults)
                Console.WriteLine(result.ToString());

            IEnumerable<Actor> actorScanResults;

            Console.WriteLine();
            Console.WriteLine("Running scan 1, expecting 2 results");
            actorScanResults = context.Scan<Actor>(
                new ScanCondition("HeightInMeters", ScanOperator.LessThan, 1.85f));
            foreach (var result in actorScanResults)
                Console.WriteLine(result.ToString());

            Console.WriteLine();
            Console.WriteLine("Running scan 2, expecting 1 result");
            Address scanAddress = new Address { City = "New York City", Country = "USA" };
            actorScanResults = context.Scan<Actor>(
                new ScanCondition("Address", ScanOperator.Equal, scanAddress));
            foreach (var result in actorScanResults)
                Console.WriteLine(result.ToString());
        }
 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;
 }
Exemple #3
0
        public Boolean InsertNewBudget(DynamoDBContext context, int UserID, string BudgetName, string BudgetCurrency, int BudgetAmmount, DateTime BudgetUpdatedDate)
        {
            Boolean insertedBudget = false;
            IEnumerable<BudgetsList> budgetsFound = context.Scan<BudgetsList>();
            int budgetID = 0;
            if (budgetsFound.LongCount() > 0)
            {
                BudgetsList lastRegistered = budgetsFound.OrderBy(dr => dr.BudgetID).Last();
                if (lastRegistered != null)
                    budgetID = lastRegistered.BudgetID + 1;
                else
                    budgetID++;
            }
            else
                budgetID++;

            try
            {
                BudgetsList newBudget = new BudgetsList();
                newBudget.BudgetID = budgetID;
                newBudget.BudgetOwnerID = UserID;
                newBudget.BudgetAmmount = BudgetAmmount;
                newBudget.BudgetCurrency = BudgetCurrency;
                newBudget.BudgetUpdatedDate = BudgetUpdatedDate;
                newBudget.BudgetName = BudgetName;
                context.Save<BudgetsList>(newBudget);
                insertedBudget = true;
            }
            catch (Exception ex)
            {
                insertedBudget = false;
            }
            return insertedBudget;
        }
Exemple #4
0
        protected Boolean CreateUserBudgetTable(DynamoDBContext context, string registerdUser)
        {
            Boolean created = false;
            Users currentUser = userCommon.GetUser(context, registerdUser);
            string tableName = $"BudgetLog_{currentUser.UserID}";
            var request = new CreateTableRequest
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                {
                    new AttributeDefinition
                    {
                        AttributeName = "BudgetLogID",
                        AttributeType = "N"
                    }
                },
                KeySchema = new List<KeySchemaElement>()
                {
                    new KeySchemaElement
                    {
                        AttributeName = "BudgetLogID",
                        KeyType = "HASH"
                    }
                },
                ProvisionedThroughput = new ProvisionedThroughput
                {
                    ReadCapacityUnits = 5,
                    WriteCapacityUnits = 2
                }
            };

            var response = client.CreateTable(request);
            int time = 0;
            var result = response.TableDescription;
            string status = result.TableStatus;
            if (status.ToLower() == "active")
                created = true;
            else
                created = false;

            while (!created)
            {
                time = time + 20;
                System.Threading.Thread.Sleep(20);
                var res = client.DescribeTable(new DescribeTableRequest { TableName = tableName });

                if (res.Table.TableStatus.Value.ToLower() == "active")
                {
                    created = true;
                    break;
                }
                else
                    created = false;

                if (time == 1000)
                    break;
            }

            return created;
        }
Exemple #5
0
        static void Main(string[] args)
        {
            var awsKey = "my-aws-key";
            var awsSecret = "my-aws-secret";
            var config = new AmazonDynamoDBConfig { ServiceURL = "http://localhost:8000" };

            var client = new AmazonDynamoDBClient(awsKey, awsSecret, config);
            var ctx = new DynamoDBContext(client);

            var userId = "theburningmonk-1";

            // query examples
            QueryByHashKey(userId, client, ctx);
            QueryWithRangeKey(userId, client, ctx);
            QueryWithOrderAndLimit(userId, client, ctx);
            QueryWithNoConsistentRead(userId, client, ctx);
            ThrottlingWithQueryPageSize(userId, client, ctx);
            SelectSpecificAttributes(userId, client, ctx);
            QueryWithNoReturnedConsumedCapacity(userId, client);
            QueryWithLocalSecondaryIndexAllAttributes(userId, client, ctx);
            QueryWithLocalSecondaryIndexProjectedAttributes(userId, client, ctx);
            QueryWithGlobalSecondaryIndexProjectedAttributes(client, ctx);

            // scan examples
            BasicScan(client, ctx);
            ScanWithLimit(client, ctx);
            ThrottlingWithScanPageSize(client, ctx);
            ScanWithScanPageSizeAndSegments(client, ctx);
            ScanWithNoReturnedConsumedCapacity(client);
            SelectSpecificAttributes(client, ctx);

            Console.WriteLine("all done...");

            Console.ReadKey();
        }
Exemple #6
0
        public Boolean InsertNewUser(DynamoDBContext context, string userName, string userPassword, string userEmail, string userSalt)
        {
            Boolean insertedUser = false;
            IEnumerable<Users> usersFound = context.Scan<Users>();
            int userID = 0;
            if (usersFound.LongCount() > 0)
            {
                Users lastRegistered = usersFound.OrderBy(dr => dr.UserID).Last();
                if (lastRegistered != null)
                    userID = lastRegistered.UserID + 1;
                else
                    userID++;
            }
            else
                userID++;

            try
            {
                Users newUser = new Users();
                newUser.UserID = userID;
                newUser.UserName = userName;
                newUser.UserPassword = userPassword;
                newUser.UserEmail = userEmail;
                newUser.UserSalt = userSalt;
                newUser.UserRegistered = false;
                context.Save<Users>(newUser);
                insertedUser = true;
            }
            catch (Exception ex)
            {
                insertedUser = false;
            }
            return insertedUser;
        }
Exemple #7
0
        public override void Run()
        {
            var req = new UpdateItemRequest()
            {
                TableName = "counters",
                UpdateExpression = "ADD id :incr",
                ReturnValues = new ReturnValue("UPDATED_NEW")
            };
            req.Key.Add("table_name", new AttributeValue("user"));
            req.ExpressionAttributeValues.Add(":incr", new AttributeValue() { N = "1" });
            req.UpdateExpression = "ADD id :incr";

            var resp = DynamoDBClient.Instance.UpdateItem(req);
            short newId = short.Parse(resp.Attributes["id"].N);

            using (var ctx = new DynamoDBContext(DynamoDBClient.Instance))
            {
                User user = new User()
                {
                    id = newId,
                    accesskey = Guid.NewGuid()
                };
                ctx.Save(user);
            }
            Console.WriteLine("User [" + newId + "] has been added");

            if (Program.IsInteractive)
                Program.ToMainMenu();
        }
Exemple #8
0
 public string GetUser(DynamoDBContext context, int UserID)
 {
     Users user = context.Load<Users>(UserID);
     if (user != null)
         return user.UserName;
     else
         return "User doesn't exist";
 }
Exemple #9
0
        public Users GetUser(DynamoDBContext context, string UserName)
        {
            IEnumerable<Users> usersFound = context.Scan<Users>(new ScanCondition("UserName", ScanOperator.Equal, UserName));

            if (usersFound.Count() == 1)
                return usersFound.First();
            else
                return null;
        }
Exemple #10
0
 public async Task<TenTwentyAgency> PutAsync([FromBody] TenTwentyAgency tenTwentyAgency,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     var now = TimeExtensions.GetPreciseUTCNow();
     tenTwentyAgency.ModifiedTime = now;
     var context = new DynamoDBContext(Settings.AmazonDynamoDBClient);
     await context.SaveAsync(tenTwentyAgency, cancellationToken);
     return tenTwentyAgency;
 }
        PollWriterManager()
        {
            this._snsClient = new AmazonSimpleNotificationServiceClient();

            this._dynamoDBClient = new AmazonDynamoDBClient();
            this._dbContext = new DynamoDBContext(this._dynamoDBClient, new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 });

            this._swfClient = new AmazonSimpleWorkflowClient();
        }
Exemple #12
0
 public async Task<TenTwentyAgency> GetAsync(Guid instanceId,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     var context = new DynamoDBContext(Settings.AmazonDynamoDBClient);
     return
         await
             context.LoadAsync<TenTwentyAgency>(instanceId.ToString(), Settings.AgenciesRangeKeyValue,
                 cancellationToken);
 }
Exemple #13
0
 // GET: Account
 public ActionResult Index()
 {
     if (Convert.ToBoolean(Session["IsAdmin"]))
     {
         DynamoDBContext context = new DynamoDBContext(client);
         List<string> userList = userHelper.GetUsers(context);
         return View(userList);
     }
     else
         return RedirectToAction("../Errors/Error404");
 }
Exemple #14
0
 public async Task<TenTwentyAgency> PostAsync([FromBody] TenTwentyAgency tenTwentyAgency,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     var now = TimeExtensions.GetPreciseUTCNow();
     tenTwentyAgency.AgencyId = Guid.NewGuid();
     tenTwentyAgency.CreatedTime = tenTwentyAgency.ModifiedTime = now;
     tenTwentyAgency.InstanceId = Settings.AgenciesRangeKeyValue;
     var context = new DynamoDBContext(Settings.AmazonDynamoDBClient);
     await context.SaveAsync(tenTwentyAgency, cancellationToken);
     return tenTwentyAgency;
 }
Exemple #15
0
        ///// <summary>
        ///// Allows the use of a specific config in the creation of the client for a context
        ///// </summary>
        ///// <param name="context">The context the client should be used in</param>
        ///// <param name="config">The config object for the client</param>
        //public static void UseConfigForClient(DynamoDBContext context, AmazonS3Config config)
        //{
        //    var castedClient = ((AmazonDynamoDBClient)context.Client);
        //    var client = new AmazonS3Client(castedClient.GetCredentials(), config);
        //    S3ClientCache cache;
        //    if (!S3Link.Caches.TryGetValue(context, out cache))
        //    {                
        //        cache = new S3ClientCache(castedClient.GetCredentials(),castedClient.CloneConfig<AmazonS3Config>());
        //        S3Link.Caches.Add(context, cache);
        //    }            
        //    cache.UseClient(client, config.RegionEndpoint);
        //}

        /// <summary>
        /// Creates an S3Link that can be used to managed an S3 connection
        /// </summary>
        /// <param name="context">The context that is handling the S3Link</param>
        /// <param name="bucket">The bucket the S3Link should manage</param>
        /// <param name="key">The key that S3Link should store and download from</param>
        /// <param name="region">The region of the S3 resource</param>
        /// <returns>A new S3Link object that can upload and download to the target bucket</returns>
        public static S3Link Create(DynamoDBContext context, string bucket, string key, Amazon.RegionEndpoint region)
        {
            S3ClientCache cacheFromKey;
            if (S3Link.Caches.TryGetValue(context, out cacheFromKey))
            {
                return new S3Link(cacheFromKey, bucket, key, region.SystemName);
            }

            S3ClientCache cache = CreatClientCacheFromContext(context);
            return new S3Link(cache, bucket, key, region.SystemName);
        }
Exemple #16
0
 public List<string> GetUsers(DynamoDBContext context)
 {
     List<string> test = new List<string>();
     IEnumerable<Users> usersFound = context.Scan<Users>();
     if (usersFound.LongCount() > 0)
     {
         foreach (Users user in usersFound)
         {
             test.Add(user.UserName);
         }
     }
     return test;
 }
Exemple #17
0
        private static void QueryByHashKey(string userId, AmazonDynamoDBClient client, DynamoDBContext context)
        {
            var selectQuery = string.Format("SELECT * FROM GameScores WHERE UserId = \"{0}\"", userId);

            Console.WriteLine("(AmazonDynamoDBClient) Running basic hash key query :\n\t\t{0}", selectQuery);
            var response = client.Query(selectQuery);
            Debug.Assert(response.Items.Count == 5);
            Debug.Assert(response.Items.TrueForAll(i => i["UserId"].S == userId));

            Console.WriteLine("(DynamoDBContext) Running basic hash key query :\n\t\t{0}", selectQuery);
            var gameScores = context.ExecQuery<GameScore>(selectQuery).ToArray();
            Debug.Assert(gameScores.Count() == 5);
            Debug.Assert(gameScores.All(gs => gs.UserId == userId));
        }
        public void LogMatches(IEnumerable<Match> matches)
        {
            using (var context = new DynamoDBContext(client))
            {
                var dynamoDbMatches = new List<DynamoDbMatch>();
                foreach(var match in matches)
                {
                    dynamoDbMatches.Add(ToDynamoDbMatch(match));
                }

                var batchWriter = context.CreateBatchWrite<DynamoDbMatch>();
                batchWriter.AddPutItems(dynamoDbMatches);
                batchWriter.Execute();
            }
        }
        public DynamoDbMatchLogger()
        {
            _preexistingMatches = new List<Match>();

            //grab all the existing matches
            List<DynamoDbMatch> dynamoDbMatches;
            using (var context = new DynamoDBContext(client))
            {
                dynamoDbMatches = context.Scan<DynamoDbMatch>().ToList();
            }

            foreach(var dynamoDbMatch in dynamoDbMatches)
            {
                _preexistingMatches.Add(ToMatch(dynamoDbMatch));
            }
        }
Exemple #20
0
        private static void QueryWithRangeKey(string userId, AmazonDynamoDBClient client, DynamoDBContext context)
        {
            var selectQuery = string.Format("SELECT * FROM GameScores WHERE UserId = \"{0}\" AND GameTitle BEGINS WITH \"A\"", userId);

            Console.WriteLine("(AmazonDynamoDBClient) Running query with range key :\n\t\t{0}", selectQuery);
            var response = client.Query(selectQuery);
            Debug.Assert(response.Items.Count == 2);
            Debug.Assert(response.Items.TrueForAll(i => i["UserId"].S == userId));
            Debug.Assert(response.Items.TrueForAll(i => i["GameTitle"].S.StartsWith("A")));

            Console.WriteLine("(DynamoDBContext) Running query with range key :\n\t\t{0}", selectQuery);

            var gameScores = context.ExecQuery<GameScore>(selectQuery).ToArray();
            Debug.Assert(gameScores.Count() == 2);
            Debug.Assert(gameScores.All(gs => gs.UserId == userId));
            Debug.Assert(gameScores.All(gs => gs.GameTitle.StartsWith("A")));
        }
Exemple #21
0
        ///// <summary>
        ///// Allows the use of a specific config in the creation of the client for a context
        ///// </summary>
        ///// <param name="context">The context the client should be used in</param>
        ///// <param name="config">The config object for the client</param>
        //public static void UseConfigForClient(DynamoDBContext context, AmazonS3Config config)
        //{
        //    var castedClient = ((AmazonDynamoDBClient)context.Client);
        //    var client = new AmazonS3Client(castedClient.GetCredentials(), config);
        //    S3ClientCache cache;
        //    if (!S3Link.Caches.TryGetValue(context, out cache))
        //    {                
        //        cache = new S3ClientCache(castedClient.GetCredentials(),castedClient.CloneConfig<AmazonS3Config>());
        //        S3Link.Caches.Add(context, cache);
        //    }            
        //    cache.UseClient(client, config.RegionEndpoint);
        //}

        /// <summary>
        /// Creates an S3Link that can be used to managed an S3 connection
        /// </summary>
        /// <param name="context">The context that is handling the S3Link</param>
        /// <param name="bucket">The bucket the S3Link should manage</param>
        /// <param name="key">The key that S3Link should store and download from</param>
        /// <param name="region">The region of the S3 resource</param>
        /// <returns>A new S3Link object that can upload and download to the target bucket</returns>
        public static S3Link Create(DynamoDBContext context, string bucket, string key, Amazon.RegionEndpoint region)
        {
            S3ClientCache cacheFromKey;
            if (S3Link.Caches.TryGetValue(context, out cacheFromKey))
            {
                return new S3Link(cacheFromKey, bucket, key, region.SystemName);
            }
            var client = ((AmazonDynamoDBClient)context.Client);
            S3ClientCache cache = new S3ClientCache(client.GetCredentials(), client.CloneConfig<AmazonS3Config>());

            lock (S3Link.cacheLock)
            {
                S3Link.Caches.Add(context, cache);                
            }

            return new S3Link(cache, bucket, key, region.SystemName);
        }
        private static async Task <Policy> RetrieveAsync(DynamoDBContext context, Policy policyToFind)
        {
            var scanConditions = new List <ScanCondition>();

            if (!string.IsNullOrEmpty(policyToFind.PolicyId))
            {
                scanConditions.Add(new ScanCondition("PolicyId", ScanOperator.Equal, policyToFind.PolicyId));
            }

            if (!string.IsNullOrEmpty(policyToFind.Coverages[0]))
            {
                scanConditions.Add(new ScanCondition("Coverages", ScanOperator.Contains, policyToFind.Coverages[0]));
            }

            var policySearch = context.ScanAsync <Policy>(scanConditions);

            var policies = await policySearch.GetNextSetAsync();

            policyToFind.coveredInd = policies.Count > 0 ? true : false;
            return(policyToFind);
        }
    protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
    {
      var records = events.Select(x => new LogDocument(x, x.RenderMessage(_formatProvider)));

      try
      {
        using (var client = new AmazonDynamoDBClient(AmazonDynamoDbConfig))
        {
          using (var context = new DynamoDBContext(client))
          {
            var batchWrite = context.CreateBatchWrite<LogDocument>(OperationConfig);
            batchWrite.AddPutItems(records);
            await batchWrite.ExecuteAsync();
          }
        }
      }
      catch (Exception exception)
      {
        SelfLog.WriteLine("Unable to write events to DynamoDB Sink for {0}: {1}", _tableName, exception);
      }
    }
        /// <summary>
        /// Sends logs to AWS DynamoDB.
        /// </summary>
        /// <param name="events">Events</param>
        /// <returns>Task</returns>
        protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events)
        {
            var records = events.Select(x => new LogDocument(x, x.RenderMessage(formatProvider)));

            try
            {
                using (var client = new AmazonDynamoDBClient(BasicAwsCredentials, AmazonDynamoDbConfig))
                {
                    using (var context = new DynamoDBContext(client))
                    {
                        var batchWrite = context.CreateBatchWrite <LogDocument>(DynamoDbOperationConfig);
                        batchWrite.AddPutItems(records);
                        await batchWrite.ExecuteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                SelfLog.WriteLine("Cannot write events to AWS DynamoDB table {0}. Exception {1}", tableName, ex);
            }
        }
Exemple #25
0
        protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events)
        {
            var records = events.Select(x => new LogDocument(x, x.RenderMessage(_formatProvider)));

            try
            {
                using (var client = new AmazonDynamoDBClient(AmazonDynamoDbConfig))
                {
                    using (var context = new DynamoDBContext(client))
                    {
                        var batchWrite = context.CreateBatchWrite <LogDocument>(OperationConfig);
                        batchWrite.AddPutItems(records);
                        await batchWrite.ExecuteAsync();
                    }
                }
            }
            catch (Exception exception)
            {
                SelfLog.WriteLine("Unable to write events to DynamoDB Sink for {0}: {1}", _tableName, exception);
            }
        }
Exemple #26
0
        public List <TEntity> GetAll()
        {
            List <TEntity> partialResultDynamo = new List <TEntity>();
            List <TEntity> totalResultDynamo   = new List <TEntity>();

            using DynamoDBContext context = GetContext();
            //Teniendo en cuenta la restricción de Dynamo en cuanto al límite de 1MB de los registros devueltos por cada consulta:
            AsyncSearch <TEntity> query = context.ScanAsync <TEntity>(null);

            do
            {
                partialResultDynamo.Clear();
                partialResultDynamo = query.GetNextSetAsync().Result.ToList();
                if (partialResultDynamo.Count > 0)                   //Si en la porción consultada obtuvo registros que cumplen con los filtros
                {
                    totalResultDynamo.AddRange(partialResultDynamo); //Añádalos.
                }
            } while (!query.IsDone);

            return(totalResultDynamo);
        }
        public async Task Confirm(ConfirmAdvertModel model)
        {
            using var client  = new AmazonDynamoDBClient();
            using var context = new DynamoDBContext(client);
            var record = await context.LoadAsync <AdvertDbModel>(model.Id);

            if (record == null)
            {
                throw new KeyNotFoundException($"A record with ID = {model.Id} was not found");
            }

            if (model.Status == AdvertStatus.Active)
            {
                record.Status = AdvertStatus.Active;
                await context.SaveAsync(record);
            }
            else
            {
                await context.DeleteAsync(record);
            }
        }
 /// <summary>Execute the NAnt task</summary>
 protected override void ExecuteTask()
 {
     // Log the update
     Project.Log(Level.Info, "Updating application '{0}' to new version '{1}' in DynamoDB", Application, Version);
     // Update DynamoDB
     using (var client = Client) {
         try {
             _context = new DynamoDBContext(client);
             var update = new WebApplication {
                 Name = Application,
                 Version = Version,
                 LastUpdate = DateTime.Now
             };
             _context.Save(update);
         } catch (AmazonDynamoDBException ex) {
             ShowError(ex);
             Environment.Exit(-1);
         }
     }
     Project.Log(Level.Info, "Successfully updated application '{0}' to version '{1}' in DynamoDB", Application, Version);
 }
Exemple #29
0
        public static bool AddItem(string url, string result)
        {
            try
            {
                var client  = new AmazonDynamoDBClient();
                var context = new DynamoDBContext(client);
                var item    = new DynamoDBItem
                {
                    url    = url,
                    result = result
                };

                context.Save(item);
            }
            catch (AmazonDynamoDBException e)
            {
                return(false);
            }

            return(true);
        }
Exemple #30
0
        public async Task <Contact> LookUpEmail()
        {
            var client          = new AmazonDynamoDBClient();
            var dbcontextconfig = new DynamoDBContextConfig();

            dbcontextconfig.TableNamePrefix = $"{this.OrgId}-";
            DynamoDBContext dbcontext = new DynamoDBContext(client, dbcontextconfig);

            try
            {
                var result = await dbcontext.LoadAsync <Contact>(this.Email.ToLower());

                Console.WriteLine($"Result of lookup {result}");
                return(result);
            }
            catch (System.Exception)
            {
                Contact C = new Contact();
                return(C);
            }
        }
Exemple #31
0
        public async Task <bool> DeleteImageAsync(AnnotationImage image)
        {
            try
            {
                // Delete image from S3
                var deleteObjectRequest = new DeleteObjectRequest
                {
                    BucketName = this._bucketName,
                    Key        = $"{image.Package.PackageName.ReplaceSpecialCharacters()}/{image.ImageName.ReplaceSpecialCharacters()}"
                };

                var response = await this._s3Client.DeleteObjectAsync(deleteObjectRequest).ConfigureAwait(false);

                // Delete image from DynamoDB
                using (var context = new DynamoDBContext(this._dynamoDbClient))
                {
                    var dbConfig = new DynamoDBOperationConfig
                    {
                        OverrideTableName = this._dbTableName
                    };
                    var package = await context.LoadAsync <AnnotationPackageDto>(image.Package.ExternalId, dbConfig).ConfigureAwait(false);

                    package.Images?.RemoveAll(o => o.ImageName.Equals(image.ImageName));
                    await context.SaveAsync(package, dbConfig).ConfigureAwait(false);
                }

                // Delete local image
                var localImagePath = Path.Combine(this._extractionFolder, image.Package.PackageName, image.ImageName);
                if (File.Exists(localImagePath))
                {
                    File.Delete(localImagePath);
                }

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
        public async Task <IActionResult> PushComment(int movieId, string movieComment)
        {
            var      context = new DynamoDBContext(dynamoDb);
            Comments item    = await ReadCommentsOfMovieAsync(movieId);

            if (item != null)
            {
                UserComment uc = new UserComment
                {
                    Id      = System.Guid.NewGuid().ToString(),
                    userId  = _userManager.GetUserId(HttpContext.User),
                    comment = movieComment
                };
                item.userComment.Add(uc);
                await context.SaveAsync(item);
            }
            else
            {
                var comment = new Comments
                {
                    movieId     = movieId,
                    userComment = new List <UserComment>
                    {
                        new UserComment
                        {
                            Id      = System.Guid.NewGuid().ToString(),
                            userId  = _userManager.GetUserId(HttpContext.User),
                            comment = movieComment
                        }
                    }
                };
                await context.SaveAsync(comment);
            }
            var movie = await _context.Movie.Include(x => x.UserMovie)
                        .FirstOrDefaultAsync(m => m.Id == movieId);

            ViewData["movieComments"] = await ReadCommentsOfMovieAsync(movie.Id);

            return(View("Details", movie));
        }
        public async Task <userResponse> getUser([FromRoute] string id)
        {
            ;
            userResponse resUser = new userResponse();

            try
            {
                var             credentials   = new Amazon.Runtime.BasicAWSCredentials(Constants.access_key, Constants.secret_key);
                var             S3Client      = new AmazonDynamoDBClient(credentials, Constants.regionEndpoint);
                var             tableName     = "users";
                DynamoDBContext context       = new DynamoDBContext(S3Client);
                var             tableResponse = await S3Client.ListTablesAsync();

                if (tableResponse.TableNames.Contains(tableName))
                {
                    var conditions = new List <ScanCondition>();
                    conditions.Add(new ScanCondition("userId", ScanOperator.Equal, id));
                    var allDocs = await context.ScanAsync <users>(conditions).GetRemainingAsync();

                    user _user = new user();
                    _user.userEmail     = allDocs[0].userEmail;
                    _user.userImageUrl  = allDocs[0].userImageUrl;
                    _user.userFirstName = allDocs[0].userFirstName;
                    _user.userId        = allDocs[0].userId;
                    _user.userLastName  = allDocs[0].userLastName;
                    _user.userName      = allDocs[0].userName;
                    _user.userPassword  = allDocs[0].userPassword;
                    resUser.user        = _user;
                    resUser.code        = (int)System.Net.HttpStatusCode.OK;
                    resUser.message     = "Success";
                }
            }
            catch (Exception ex)
            {
                resUser.code    = (int)System.Net.HttpStatusCode.BadGateway;
                resUser.message = ex.Message;
            }

            return(resUser);
        }
        public async Task <List <UniqueName> > ListAsync(Guid accountId, int start, int limit)
        {
            var stopwatch = Stopwatch.StartNew();

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

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

                // TODO: Figure out how to specify start and limit

                var hashKeyValue = accountId;
                AsyncSearch <UniqueName> asyncSearch = context.QueryAsync <UniqueName>(hashKeyValue, operationConfig);

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

                return(items);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, "Exception loading unique names: ");
                throw;
            }
            finally
            {
                stopwatch.Stop();
                Logger.LogMessage("Query unique names took: {0}ms", stopwatch.ElapsedMilliseconds);
            }
        }
Exemple #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VehicleInventoryScheduledEventProcessor" /> class.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="environment">The environment.</param>
        public VehicleInventoryScheduledEventProcessor(IElasticClient client, string environment)
        {
            if (client == null)
            {
                var creds =
                    new StaticCredentialsProvider(
                        new AwsCredentials
                {
                    AccessKey = "",
                    SecretKey = "",
                });

                var node =
                    new SingleNodeConnectionPool(
                        new Uri(Environment.GetEnvironmentVariable("elasticSearchURL")));

                this.awsHttpConnection = new AwsHttpConnection(RegionEndpoint.USEast1.SystemName, creds);

                // setup index settings for each strongly typed object
                var settings =
                    new ConnectionSettings(node, this.awsHttpConnection)
                    .DisableDirectStreaming()
                    .InferMappingFor <InventoryItem>(m => m.IdProperty(p => p.VIN))
                    .MapDefaultTypeIndices(m => m.Add(typeof(InventoryItem), "dev_vehicle_inventory"));

                this.elasticClient = new ElasticClient(settings);

                IAmazonDynamoDB dynamoDbClient = new AmazonDynamoDBClient(RegionEndpoint.USEast1);
                this.indexer = new ElasticSearchIndexer <InventoryItem>(dynamoDbClient, Environment.GetEnvironmentVariable("environment"), this.elasticClient);

                var config = new DynamoDBContextConfig {
                    ConsistentRead = true, TableNamePrefix = $"{Environment.GetEnvironmentVariable("environment")}_"
                };
                this.dynamoDbContext = new DynamoDBContext(dynamoDbClient, config);
            }
            else
            {
                this.elasticClient = client;
            }
        }
Exemple #36
0
        public async Task <IdentityResult> UpdateAsync(ApplicationRole role, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ApplicationRole updatedRole = await FindByNameAsync(role.NormalizedRoleName, cancellationToken);

            if (updatedRole == null)
            {
                return(IdentityResult.Failed());
            }

            updatedRole.RoleId             = role.RoleId;
            updatedRole.RoleName           = role.RoleName;
            updatedRole.NormalizedRoleName = role.NormalizedRoleName;

            DynamoDBContext context = new DynamoDBContext(_client);
            var             roleDoc = context.ToDocument <ApplicationRole>(updatedRole);
            Table           table   = Table.LoadTable(_client, "ApplicationRole");
            await table.PutItemAsync(roleDoc);

            return(IdentityResult.Success);
        }
        public async Task <IActionResult> GetMetadata([FromRoute] int accountId)
        {
            var userId = _tenantProvider.GetTenantId();

            using (var context = new DynamoDBContext(_dynamoDb))
            {
                var accountMetadata = await context.LoadAsync <AccountMetadata>(userId, accountId);

                if (accountMetadata == null)
                {
                    return(NotFound());
                }

                return(Ok(new AccountMetadataViewModel
                {
                    Nickname = accountMetadata.Nickname,
                    AccountId = accountMetadata.AccountId,
                    UserId = accountMetadata.UserId,
                    ImageUrl = accountMetadata.ImageUrl,
                }));
            }
        }
Exemple #38
0
        static async Task <Entry> UpdateTableItemAsync(bool debug, IAmazonDynamoDB client, string id, string status)
        {
            DebugPrint(debug, "Setting the status of item #" + id + " to: " + status);

            DynamoDBContext context = new DynamoDBContext(client);

            // Retrieve the existing order
            Entry orderRetrieved = await context.LoadAsync <Entry>(id, "Order");

            // Update status
            orderRetrieved.Order_Status = status;
            await context.SaveAsync(orderRetrieved);

            // Retrieve the updated item
            Entry updatedOrder = await context.LoadAsync <Entry>(id, "Order", new DynamoDBOperationConfig
            {
                ConsistentRead = true
            },
                                                                 new System.Threading.CancellationToken());

            return(updatedOrder);
        }
Exemple #39
0
    private void GetTableLength(DynamoDBContext context)
    {
        PlacedObject placedObject = null;

        context.LoadAsync <PlacedObject>(1, (result) => // one for starter object meant to hold object count
        {
            if (result.Exception == null)
            {
                placedObject = result.Result as PlacedObject;
                // Update few properties.
                //placedObject.CompassAngle += 1; // to add to the total amount of objects placed in world
                m_TableLength = (int)placedObject.CompassAngle;
                context.SaveAsync <PlacedObject>(placedObject, (res) =>
                {
                    if (res.Exception == null)
                    {
                        Debug.Log("Table Length Acquired");
                    }
                });
            }
        });
    }
Exemple #40
0
    // Use this for initialization
    void Start()
    {
        m_TableLength = 0;
        UnityInitializer.AttachToGameObject(this.gameObject);

        var credentials             = new CognitoAWSCredentials("us-east-1:4a6bd71a-2349-4b3f-9f10-e2865187b87a", RegionEndpoint.USEast1);
        AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);

        Context = new DynamoDBContext(client);

        var request = new DescribeTableRequest
        {
            TableName = @"AppathonTable"
        };

        client.DescribeTableAsync(request, (result) =>
        {
            if (result.Exception != null)
            {
                Debug.Log(result.Exception);
                return;
            }
            var response = result.Response;
            TableDescription description = response.Table;
            Debug.Log("# of items: " + response.Table.ItemCount + "\n");
            m_TableLength = (int)response.Table.ItemCount;
            Debug.Log("Provision Throughput (reads/sec): " +
                      description.ProvisionedThroughput.ReadCapacityUnits + "\n");
            //StartCoroutine(CheckTableLength(Context));
        }, null);

        GetTableLength(Context); // first gets table length then calls the Acquring function, this should only need to happen once
        //StartCoroutine(CheckTableLength(Context));
        //SimpleAddObjectToDB(Context);
        //SimpleRetrieveObject(Context);
        //DeleteObjectFromDB(Context);
        StartCoroutine(GetLocationWait());
        //AddObjectToDB(Context);
    }
Exemple #41
0
        public async static Task gettransactionq(DynamoDBContext context, string accountid = "123")
        {
            try
            {
                DateTime twoWeeksAgoDate    = DateTime.UtcNow - TimeSpan.FromDays(15);
                var      latestRepliesserch =
                    context.QueryAsync <Transaction>(accountid, QueryOperator.GreaterThan, new List <object> {
                    twoWeeksAgoDate
                });
                Console.WriteLine("\nFindRepliesInLast15Days: Printing result.....");
                var latestReplies = await latestRepliesserch.GetNextSetAsync();

                foreach (Transaction r in latestReplies)
                {
                    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", r.accountid, r.created, r.balance, r.interest, r.accountname);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task <AnnotationConfig> GetAnnotationConfigAsync()
        {
            try
            {
                using (var context = new DynamoDBContext(this._dynamoDbClient))
                {
                    var annotationConfig = await context.LoadAsync <AnnotationConfigDto>(this._configHashKey).ConfigureAwait(false);

                    return(new AnnotationConfig
                    {
                        ObjectClasses = annotationConfig.ObjectClasses,
                        Tags = annotationConfig.Tags.Select(o => new Model.AnnotationPackageTag {
                            Value = o
                        }).ToList()
                    });
                }
            }
            catch (Exception)
            {
                return(await Task.FromResult <AnnotationConfig>(null));
            }
        }
Exemple #43
0
        public IActionResult AddNewRoom([FromBody] Rooms newRoom)
        {
            DynamoDBContext aws_Context = new DynamoDBContext(client);

            if (newRoom == null)
            {
                return(BadRequest());
            }
            else
            {
                try
                {
                    //If user is Admin HouseKeeper,Status is must empty
                    Rooms room = new Rooms
                    {
                        Id           = newRoom.Id,
                        RoomNumber   = newRoom.RoomNumber,
                        BaseMaterial = newRoom.BaseMaterial,
                        CheckDate    = DateTime.Now,
                        Status       = newRoom.Status,
                        HouseKeeper  = newRoom.HouseKeeper,
                        Note         = newRoom.Note,
                        creator      = newRoom.creator
                    };


                    aws_Context.SaveAsync(room);
                    _context.Room.Add(newRoom);
                    _context.SaveChanges();
                }

                catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
                catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }


            return(CreatedAtRoute("GetRoom", new { id = newRoom.Id }, newRoom));
        }
Exemple #44
0
        public async Task <List <Book> > GetBooksAsync()
        {
            ScanFilter scanFilter = new ScanFilter();

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

            ScanOperationConfig soc = new ScanOperationConfig()
            {
                // AttributesToGet = new List { "Id", "Title", "ISBN", "Price" },
                Filter = scanFilter
            };
            DynamoDBContext    context      = new DynamoDBContext(dynamoDBClient);
            AsyncSearch <Book> search       = context.FromScanAsync <Book>(soc, null);
            List <Book>        documentList = new List <Book>();

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

            return(documentList);
        }
Exemple #45
0
        public UserManager()
        {
            // Check to see if a table name was passed in through environment variables and if so
            // add the table mapping.
            var tableName = System.Environment.GetEnvironmentVariable(TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP);

            if (!string.IsNullOrEmpty(tableName))
            {
                AWSConfigsDynamoDB.Context.TypeMappings[typeof(User)] = new Amazon.Util.TypeMapping(typeof(User), tableName);
            }

            var config = new DynamoDBContextConfig {
                Conversion = DynamoDBEntryConversion.V2
            };

            DDBContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };
        }
Exemple #46
0
        public async Task <bool> DeleteUserByEmail(string email)
        {
            try
            {
                if (!string.IsNullOrEmpty(email))
                {
                    using (client = new AmazonDynamoDBClient())
                    {
                        DynamoDBContext context = new DynamoDBContext(client);
                        //Table tbl = Table.LoadTable(client, "User", DynamoDBEntryConversion.V2);
                        await context.DeleteAsync <User>(email);

                        return(true);
                    }
                }
                return(false);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public async Task Confirm(ConfirmAdvertModel model)
        {
            using (var client = new AmazonDynamoDBClient()){
                using (var context = new DynamoDBContext(client)){
                    var record = await context.LoadAsync <AdvertDBModel>(model.Id);

                    if (record == null)
                    {
                        throw new KeyNotFoundException("Record With" + model.Id + "Not found");
                    }
                    if (model.Status == AdvertStatus.Active)
                    {
                        record.Status = AdvertStatus.Active;
                        await context.SaveAsync(record);
                    }
                    else
                    {
                        await context.DeleteAsync(record);
                    }
                }
            }
        }
Exemple #48
0
 public ActionResult Login(string userName, string userPassword)
 {
     if (userName.Length > 1 & userPassword.Trim().Length > 1)
     {
         DynamoDBContext context = new DynamoDBContext(client);
         Users loggingInUser = userHelper.GetUser(context, userName);
         if (Convert.ToString(loggingInUser) != "")
         {
             if (PasswordsMatch(userPassword, loggingInUser))
             {
                 SharedSession["LoggedInUser"] = loggingInUser;
                 return RedirectToAction("../Home/Index");
             }
             else
                 return SetResponseMessage("Invalid username or password!");
         }
         else
             return SetResponseMessage("Invalid username or password!");
     }
     else
         return SetResponseMessage("Please enter a correct length username or password");
 }
Exemple #49
0
        public async Task <List <Coupon> > GetCouponByStore(String storeName)
        {
            CreateTable();
            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("StoreName", ScanOperator.Equal, storeName);

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

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

            return(documentList);
        }
        /// <summary>
        /// Stores the client async.
        /// </summary>
        /// <returns>The client async.</returns>
        /// <param name="item">Item.</param>
        public async Task StoreClientAsync(Client item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            try
            {
                using (var context = new DynamoDBContext(client, ddbConfig))
                {
                    await context.SaveAsync(item.GetClientDynamoDB());
                }
            }
            catch (Exception ex)
            {
                logger.LogError(default(EventId), ex, "ClientRepository.StoreClientAsync failed with Client {item}", item);
                throw;
            }

            await Task.CompletedTask;
        }
Exemple #51
0
        private void button2_Click(object sender, EventArgs e)
        {
            AmazonDynamoDBClient client  = new AmazonDynamoDBClient();
            DynamoDBContext      context = new DynamoDBContext(client);

            try
            {
                if (idFuncionario.Text != "")
                {
                    dataGridView1.DataSource = ComandoAWS.SearchDataTabelaServicos(context, "", idFuncionario.Text, "", "", "", "");
                }
                else if (cidadeDestinatario.Text != "")
                {
                    dataGridView1.DataSource = ComandoAWS.SearchDataTabelaServicos(context, "", "", cidadeDestinatario.Text, "", "", "");
                }
                else if (xml.Text != "")
                {
                    dataGridView1.DataSource = ComandoAWS.SearchDataTabelaServicos(context, xml.Text, "", "", "", "", "");
                }
                else
                {
                    dataGridView1.DataSource = ComandoAWS.SearchDataTabelaServicos(context, "", "", "", "", "", "");
                }

                idFuncionario.Clear();
                cidadeDestinatario.Clear();
                status.Clear();
                comboBox1.SelectedIndex = -1;
                comboBox2.SelectedIndex = -1;
                comboBox3.SelectedIndex = -1;
            }



            catch
            {
                Console.WriteLine("Erro na busca!");
            }
        }
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Login Client Started");
        AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;
        awsCredentials        = new CognitoAWSCredentials(
            "ap-south-1:0edf52b9-63a5-4fbe-9299-aa9c9413aa2d", // Identity pool ID
            RegionEndpoint.APSouth1                            // Region
            );
        syncManager = new CognitoSyncManager(awsCredentials, RegionEndpoint.APSouth1);
        dbClient    = new AmazonDynamoDBClient(awsCredentials, RegionEndpoint.APSouth1);
        dbContext   = new DynamoDBContext(dbClient);
        playerInfo  = syncManager.OpenOrCreateDataset("playerInfo");
        playerInfo.OnSyncSuccess += SyncSuccessCallBack;
        playerInfo.OnSyncFailure += HandleSyncFailure;
        fbandcsInitiated          = fbandcsInitiated + 1;
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestEmail().RequestIdToken().RequestServerAuthCode(false).Build();

        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
        //Social.localUser.Authenticate(GoogleLoginCallback);
    }
Exemple #53
0
        public async Task <IActionResult> GetDashboardStats()
        {
            using (var context = new DynamoDBContext(_dynamoDb)) {
                // Per day
                var usersPerDay          = new List <object>();
                var totPerDay            = new List <object>();
                var avgLongSessionPerDay = new List <object>();
                var now        = DateTime.UtcNow;
                var yearForDay = now.Year;

                for (int i = 9; i >= 0; i--)   // Last 10 days including today
                {
                    var day     = now.AddDays(-i);
                    var key     = $"{yearForDay}-{day.DayOfYear}";
                    var dayStat = await context.LoadAsync <DbGrandTotalDay>(key);

                    var dayStr = day.ToString("ddd MMM d");
                    usersPerDay.Add(new {
                        key   = dayStr,
                        value = dayStat?.UserCount ?? 0
                    });
                    totPerDay.Add(new {
                        key   = dayStr,
                        value = Math.Round((dayStat?.TotalMS ?? 0) / 60000.0)
                    });
                    avgLongSessionPerDay.Add(new {
                        key   = dayStr,
                        value = Math.Round((dayStat?.AvgLongSessionMS ?? 0) / 1000.0)
                    });
                }
                return(Ok(new {
                    result = "ok",
                    usersPerDay = usersPerDay,
                    totPerDay = totPerDay,
                    avgLongSessionPerDay = avgLongSessionPerDay,
                }));
            }
        }
Exemple #54
0
        public static String SearchFuncionarios(DynamoDBContext context, String coluna, String item, String Return)
        {
            String resultado = "";
            IEnumerable <Funcionarios> funcionariosScanResults;

            Console.WriteLine();
            funcionariosScanResults = context.Scan <Funcionarios>(new ScanCondition(coluna.ToLower(), ScanOperator.Equal, item.ToLower()));

            if (Return == "id")
            {
                foreach (var result in funcionariosScanResults)
                {
                    resultado = (resultado = result.id);
                }
            }
            if (Return == "nome")
            {
                foreach (var result in funcionariosScanResults)
                {
                    resultado = (resultado = result.nome);
                }
            }

            if (resultado == "")
            {
                return("Não Encontrado");
            }

            else
            {
                List <Funcionarios> asList = funcionariosScanResults.ToList();
                asList.ForEach(Console.WriteLine);

                Console.WriteLine(asList[0].nome);

                return(resultado);
            }
        }
Exemple #55
0
        protected void BudgetRepeater_Init(object sender, EventArgs e)
        {
            if (Session["LoggedInUser"] != null)
            {
                Users loggedInUser = (Users)Session["LoggedInUser"];
                Repeater bugetRepeater = (Repeater)sender;
                DynamoDBContext context = new DynamoDBContext(client);
                BudgetsCode budgetCode = new BudgetsCode();
                IEnumerable<BudgetsList> budgets;
                if (Session["Budgets"] == null)
                {
                    budgets = budgetCode.GetBudgets(context, loggedInUser.UserID);
                    Session["Budgets"] = budgets;
                }
                else
                {
                    budgets = (IEnumerable<BudgetsList>)Session["Budgets"];
                }

                if (budgets.Count() > 0)
                {
                    bugetRepeater.Visible = true;
                    ErrorLabel.Visible = false;
                    bugetRepeater.DataSource = budgets;
                    bugetRepeater.DataBind();

                }
                else
                {
                    bugetRepeater.Visible = false;
                    ErrorLabel.Visible = true;
                }

            }
            else
                Response.Redirect("~/Account/Login.aspx", true);
        }
Exemple #56
0
 protected void LoginUser_Click(object sender, EventArgs e)
 {
     if (TextBox1.Text.Trim().Length > 1 & TextBox2.Text.Trim().Length > 1)
     {
         DynamoDBContext context = new DynamoDBContext(client);
         string userName = TextBox1.Text;
         Users loggingInUser = userCommon.GetUser(context, userName);
         if (Convert.ToString(loggingInUser) != "")
         {
             string typedPassword = TextBox2.Text;
             if (PasswordsMatch(typedPassword, loggingInUser))
             {
                 Session["LoggedInUser"] = loggingInUser;
                 Response.Redirect("~/Default.aspx");
             }
             else
                 SetResponseMessage("Invalid username or password!");
         }
         else
             SetResponseMessage("Invalid username or password!");
     }
     else
         SetResponseMessage("Please enter a correct length username or password");
 }
Exemple #57
0
 internal BatchGet(DynamoDBContext context, DynamoDBFlatConfig config)
 {
     Context = context;
     Config = config;
     Keys = new List<Key>();
 }
Exemple #58
0
        public static void PopulateMovies()
        {
            Console.WriteLine("Creating the context object");
            DynamoDBContext context = new DynamoDBContext(Database.Client);

            Console.WriteLine("Creating actors");
            Actor christianBale = new Actor
            {
                Name = "Christian Bale",
                Bio = "Christian Charles Philip Bale is an excellent horseman and an avid reader.",
                BirthDate = new DateTime(1974, 1, 30),
                Address = new Address
                {
                    City = "Los Angeles",
                    Country = "USA"
                },
                HeightInMeters = 1.83f
            };
            Actor michaelCaine = new Actor
            {
                Name = "Michael Caine",
                Bio = "Maurice Joseph Micklewhite is an English actor, better known as Michael Caine",
                BirthDate = new DateTime(1933, 3, 14),
                Address = new Address
                {
                    City = "London",
                    Country = "England"
                },
                HeightInMeters = 1.88f
            };

            Console.WriteLine("Creating movie");
            Movie darkKnight = new Movie
            {
                Title = "The Dark Knight",
                ReleaseDate = new DateTime(2008, 7, 18),
                Genres = new List<string> { "Action", "Crime", "Drama" },
                ActorNames = new List<string>
                {
                    christianBale.Name,
                    michaelCaine.Name
                }
            };

            Console.WriteLine("Saving actors and movie");
            context.Save<Actor>(michaelCaine);
            context.Save<Actor>(christianBale);
            context.Save<Movie>(darkKnight);

            Console.WriteLine("Creating and saving new actor");
            Actor maggieGyllenhaal = new Actor
            {
                Name = "Maggie Gyllenhaal",
                BirthDate = new DateTime(1977, 11, 16),
                Bio = "Maggie Gyllenhaal studied briefly at the Royal Academy of Dramatic Arts in London.",
                Address = new Address
                {
                    City = "New York City",
                    Country = "USA"
                },
                HeightInMeters = 1.75f
            };
            context.Save<Actor>(maggieGyllenhaal);

            Console.WriteLine();
            Console.WriteLine("Loading existing movie");
            Movie existingMovie = context.Load<Movie>("The Dark Knight", new DateTime(2008, 7, 18));
            Console.WriteLine(existingMovie.ToString());

            Console.WriteLine();
            Console.WriteLine("Loading nonexistent movie");
            Movie nonexistentMovie = context.Load<Movie>("The Dark Knight", new DateTime(2008, 7, 19));
            Console.WriteLine("Movie is null : " + (nonexistentMovie == null));

            Console.WriteLine("Updating movie and saving");
            existingMovie.ActorNames.Add(maggieGyllenhaal.Name);
            existingMovie.Genres.Add("Thriller");
            context.Save<Movie>(existingMovie);

            Console.WriteLine("Adding movie with same hash key but different range key");
            Movie darkKnight89 = new Movie
            {
                Title = "The Dark Knight",
                Genres = new List<string> { "Drama" },
                ReleaseDate = new DateTime(1989, 2, 23),
                ActorNames = new List<string>
                {
                    "Juan Diego",
                    "Fernando Guillén",
                    "Manuel de Blas"
                }
            };
            context.Save<Movie>(darkKnight89);
        }
Exemple #59
0
 internal BatchWrite(DynamoDBContext context, DynamoDBFlatConfig config)
 {
     Context = context;
     Config = config;
 }
 public SearchDataController()
 {
     _client = new AmazonDynamoDBClient();
     _context = new DynamoDBContext(_client);
 }