Exemplo n.º 1
0
        public static void AddDynamoDB(this IServiceCollection services, IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            if (hostingEnvironment.IsDevelopment())
            {
                var dynamoDBConfig = configuration.GetSection("DynamoDB");
                var client         = new AmazonDynamoDBClient(dynamoDBConfig["AccessKey"],
                                                              dynamoDBConfig["SecretKey"],
                                                              new AmazonDynamoDBConfig
                {
                    ServiceURL = dynamoDBConfig["ServiceURL"]
                });

                services.AddSingleton <IAmazonDynamoDB>(client);

                var pocoDynamo = new PocoDynamo(client);

                services.AddSingleton <IPocoDynamo>(pocoDynamo);

                pocoDynamo.RegisterTable <Tariff>();
                pocoDynamo.InitSchema();
            }
            else if (hostingEnvironment.EnvironmentName != "Test")
            {
                services.AddDefaultAWSOptions(configuration.GetAWSOptions());
                services.AddAWSService <IAmazonDynamoDB>();
                services.AddSingleton <IPocoDynamo>(p => new PocoDynamo(p.GetService <IAmazonDynamoDB>()));
            }

            services.AddScoped <IDynamoDBContext, DynamoDBContext>();
        }
Exemplo n.º 2
0
        public void StoreResponse_WithValidRequestId_StoresResponse()
        {
            var sut = CreateSut();

            sut.PurgeData <Requests>();
            sut.PurgeData <Responses>();

            var requestId = sut.StoreRequest("/test", HttpMethod.Get, "test".ToAsciiBytes());

            Expression <Func <Request, bool> > expr = r => r.Content.Contains("test");

            sut.StoreResponse(requestId, "test", expr.ToString(), "test".ToAsciiBytes());

            var dynamo = new PocoDynamo(CreateAmazonDynamoDbClientWithLocalDbInstance());

            var response = dynamo.Scan <Responses>(new ScanRequest("Responses"))
                           .First(r => r.RequestId == requestId);

            response.ImposterName
            .Should().Be("test");
            response.RequestId
            .Should().Be(requestId);
            response.ResponsePayloadBase64
            .Should().Be("test".ToAsciiBytes().ToBase64String());
            response.MatchedCondition
            .Should().Be(expr.ToString());
        }
Exemplo n.º 3
0
        // UpdateProfile()
        public void UpdateProfile(List <string> data, string UserName)
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <Users>();

                db.UpdateItem(UserName,
                              put: () => new Users
                {
                    FirstName = data[0],
                    LastName  = data[1],
                    Email     = data[2],
                    Telephone = data[3],
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> UpdateProfile(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 4
0
        // EditUser()
        public void EditUser(Users EditUser)
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <Users>();

                db.UpdateItem(EditUser.UserName,
                              put: () => new Users
                {
                    FirstName = EditUser.FirstName,
                    LastName  = EditUser.LastName,
                    Email     = EditUser.Email,
                    IdCard    = EditUser.IdCard,
                    IdRole    = EditUser.IdRole,
                    Telephone = EditUser.Telephone,
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> EditUser(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 5
0
        public static IPocoDynamo CreatePocoDynamo()
        {
            var dynamoClient = CreateDynamoDbClient();
            var db           = new PocoDynamo(dynamoClient);

            return(db);
        }
Exemplo n.º 6
0
        // UpdateSecretCode()
        private string _UpdateSecretCode(string UserName)
        {
            var db            = new PocoDynamo(con.GetClient());
            var NewSecretCode = _CreateRandomPassword();

            try
            {
                db.RegisterTable <Users>();

                db.UpdateItem(UserName,
                              put: () => new Users
                {
                    SecretCode = _tools.Encrypt(NewSecretCode)
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> UpdateSecretCode(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
            return(NewSecretCode);
        }
Exemplo n.º 7
0
        // GetInfo()
        public int GetData2(string IdSwitch)
        {
            Debug.WriteLine(IdSwitch);

            var db = new PocoDynamo(con.GetClient());
            var r  = 0;

            try
            {
                var q        = db.FromQuery <testData>(x => x.Id == IdSwitch);
                var dbOrders = db.Query(q).Last();

                var results = dbOrders;
                r = results.payload.Medicion;
                Debug.WriteLine(results.Id);
                Debug.WriteLine(r);
                Debug.WriteLine(results.payload.Time);

                //res = db.ScanAll<testData>().Where(x => x.Id == "thing01/data").ToArray();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MPanels -> GetInfo(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
            return(r);
        }
Exemplo n.º 8
0
        // DeletePanel()
        public void DeletePanel(string IdPanel)
        {
            var db = new PocoDynamo(con.GetClient());

            db.RegisterTable <Panels>();

            try
            {
                db.DeleteItem <Panels>(IdPanel);

                db.RegisterTable <SwitchInfo>();
                for (int i = 0; i < 42; i++)
                {
                    db.DeleteItem <SwitchInfo>(IdPanel + "_S" + i);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MPanels -> DeletePanel(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 9
0
        // UpdatePanel()
        public void UpdatePanel(Panels PanelInfo)
        {
            var db = new PocoDynamo(con.GetClient());

            db.RegisterTable <Panels>();

            try
            {
                db.UpdateItem(PanelInfo.IdPanel,
                              put: () => new Panels
                {
                    Model       = PanelInfo.Model,
                    Description = PanelInfo.Description,
                    Bus         = PanelInfo.Bus,
                    Main        = PanelInfo.Main,
                    Area        = PanelInfo.Area,
                    From        = PanelInfo.From,
                    Comments    = PanelInfo.Comments,
                    Voltage     = PanelInfo.Voltage,
                    Phases      = PanelInfo.Phases,
                    Threads     = PanelInfo.Threads,
                    Frequency   = PanelInfo.Frequency
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MPanels -> UpdatePanel(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 10
0
        public override IUserAuthRepository CreateAuthRepo()
        {
            var db           = new PocoDynamo(DynamoConfig.CreateDynamoDBClient());
            var dynamoDbRepo = new DynamoDbAuthRepository(db);

            InitTest(dynamoDbRepo);
            dynamoDbRepo.InitSchema();
            return(dynamoDbRepo);
        }
Exemplo n.º 11
0
 public void Save <T>(T value) where T : class
 {
     using (AmazonDynamoDBClient raw = new AmazonDynamoDBClient(GetCredentials(), RegionEndpoint.APSoutheast2))
     {
         var dynamo = new PocoDynamo(raw);
         dynamo.RegisterTable <T>();
         dynamo.InitSchema();
         dynamo.PutItem(value);
     }
 }
Exemplo n.º 12
0
 public List <AppreciationCards.Models.Messages> Get()
 {
     using (AmazonDynamoDBClient raw = new AmazonDynamoDBClient(GetCredentials(), RegionEndpoint.APSoutheast2))
     {
         var dynamo  = new PocoDynamo(raw);
         var request = new ScanRequest
         {
             TableName = "Messages",
         };
         return(QueryDB(request, raw));
     }
 }
Exemplo n.º 13
0
        protected override ServiceStackHost CreateAppHost()
        {
            var pocoDynamo = new PocoDynamo(CreateDynamoDBClient());

            pocoDynamo.DeleteAllTables(TimeSpan.FromMinutes(1));

            return(new AppHost
            {
                EnableAuth = true,
                Use = container => container.Register <IAuthRepository>(c => new DynamoDbAuthRepository(pocoDynamo))
            });
        }
Exemplo n.º 14
0
        // CreateTable()
        public void CreateTable()
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <Phrases>();
                db.InitSchema();

                List <string> phrases = new List <string>();
                phrases.Add("Para ganar en la vida, antes hay que saber perder");
                phrases.Add("Educa a los niños, y no será necesario castigar a los hombres");
                phrases.Add("Vive el presente sin olvidar el pasado, pero mirando siempre hacia el futuro");
                phrases.Add("La gente inteligente cuida lo que dice, respeta lo que escucha y medita lo que calla");
                phrases.Add("Si quieres una mano que te ayude, la encontraras al final de tu brazo");
                phrases.Add("La medida de la inteligencia es la habilidad para cambiar y adaptarse");
                phrases.Add("La mente es como un paracaídas, sólo funciona si se abre");
                phrases.Add("Eres el juez de tus propios actos y el árbitro de tu propio destino");
                phrases.Add("El dinero hace personas ricas, el conocimiento hace personas sabias, la humildad hace grandes personas");
                phrases.Add("Hace falta toda una vida para aprender a vivir");
                phrases.Add("No es sabia el que sabe sino el que no sabe y quiere aprender");
                phrases.Add("La sabiduría comienza donde termina el conocimiento");
                phrases.Add("Aprende del pasado, vive el presente y trabaja para el futuro");
                phrases.Add("En la vida algunas veces se gana, otras veces se aprende");
                phrases.Add("Un hombre inteligente jamás se irritaría, si tuviera delante siempre un espejo y se viera cuando discute");
                phrases.Add("Si quieres algo que nunca tuviste, debes hacer algo que nunca hiciste");
                phrases.Add("Lo malo de aprender con la experiencia, es que nunca nos graduamos");
                phrases.Add("El mayor defecto de los defectos es no darse cuenta de ninguno de ellos");
                phrases.Add("Experiencia es lo que conseguimos cuando no leemos las instrucciones");
                phrases.Add("Un tropezón puede prevenir una caída");

                for (int i = 1; i < 21; i++)
                {
                    var pharse = new Phrases
                    {
                        Id     = i,
                        Phrase = phrases[i - 1]
                    };

                    db.PutItem(pharse);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MPhrases -> CreateTable(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 15
0
        // CreateSwitch()
        public void CreateSwitch(SwitchInfo NewSwitch)
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <SwitchInfo>();
                db.PutItem(NewSwitch);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitchInfo -> CreateSwitch(). \nDescripción: " + ex.Message);
            }
        }
Exemplo n.º 16
0
        // DeleteSwitch()
        public void DeleteSwitch(string IdSwitch)
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <DATA.Switch>();
                db.DeleteItem <DATA.Switch>(IdSwitch);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitchInfo -> GetPanelSwitches(). \nDescripción: " + ex.Message);
            }
        }
Exemplo n.º 17
0
        // GetInfo()
        public SwitchInfo[] GetInfo(string IdSwitch)
        {
            SwitchInfo[] res = { };
            var          db  = new PocoDynamo(con.GetClient());

            try
            {
                res = db.ScanAll <SwitchInfo>().Where(x => x.IdSwitch == IdSwitch).ToArray();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitchInfo -> GetPanelSwitches(). \nDescripción: " + ex.Message);
            }
            return(res);
        }
Exemplo n.º 18
0
        public void CreatesTables_WhenNoTablesExists_CanCreateSchemaInAmazonAwsDynamoDb()
        {
            var configuration = LoadConfiguration();
            var options       = configuration.GetAWSOptions();

            var client = options.CreateServiceClient <IAmazonDynamoDB>();

            new AwsDynamoDbDataStore(client);

            var dynamo = new PocoDynamo(client);

            dynamo.GetTableNames()
            .Any(t => t.Equals(nameof(Sessions)))
            .Should().BeTrue();
        }
Exemplo n.º 19
0
        // GetUsersInfo()
        public Users[] GetUsersInfo()
        {
            Users[] res = { };
            var     db  = new PocoDynamo(con.GetClient());

            try
            {
                res = db.ScanAll <Users>().ToArray();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> GetUsersInfo(). \nDescripción: " + ex.Message);
            }
            return(res);
        }
Exemplo n.º 20
0
        public void CreatesTables_WhenNoTablesExists_CanCreateSchemaInLocalDynamoDbInstance()
        {
            CreateSut();

            var dynamo = new PocoDynamo(CreateAmazonDynamoDbClientWithLocalDbInstance());

            var tableNames = dynamo.GetTableNames();

            tableNames.Any(t => t.Equals(nameof(Sessions)))
            .Should().BeTrue();
            tableNames.Any(t => t.Equals(nameof(Requests)))
            .Should().BeTrue();
            tableNames.Any(t => t.Equals(nameof(Responses)))
            .Should().BeTrue();
        }
Exemplo n.º 21
0
        public static void AddPocoDynamo(this IServiceCollection services, AmazonDynamoDBConfig config)
        {
            var dynamoClient = new AmazonDynamoDBClient(config);
            var pocoDynamo   = new PocoDynamo(dynamoClient);

            // register entities
            var entities = Assembly.GetAssembly(typeof(BaseEntity))?.GetTypes()
                           .Where(t => t.BaseType == typeof(BaseEntity)).ToList();

            foreach (var entity in entities ?? new List <Type>())
            {
                pocoDynamo.RegisterTable(entity);
            }

            pocoDynamo.InitSchema();
            services.AddSingleton <IPocoDynamo>(pocoDynamo);
        }
Exemplo n.º 22
0
        // DropTable()
        public void DropTable()
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.DeleteTable <SwitchInfo>();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitchInfo -> DropTable(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 23
0
 public List <AppreciationCards.Models.Messages> GetUnread()
 {
     using (AmazonDynamoDBClient raw = new AmazonDynamoDBClient(GetCredentials(), RegionEndpoint.APSoutheast2))
     {
         var dynamo  = new PocoDynamo(raw);
         var request = new ScanRequest
         {
             TableName = "Messages",
             ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                 { ":val", new AttributeValue {
                       S = "true"
                   } }
             },
             FilterExpression = "Unread = :val",
         };
         return(QueryDB(request, raw));
     }
 }
Exemplo n.º 24
0
        // GetData()
        public DATA.Switch[] GetData(string IdSwitch)
        {
            DATA.Switch[] res = { };
            var           db  = new PocoDynamo(con.GetClient());

            try
            {
                res = db.ScanAll <DATA.Switch>().Where(x => x.IdSwitch == IdSwitch).ToArray();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitch -> GetData(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
            return(res);
        }
Exemplo n.º 25
0
        public int CountFiles(string IdSwitch)
        {
            var db  = new PocoDynamo(con.GetClient());
            var res = 0;

            try
            {
                res = db.ScanAll <Files>().Where(x => x.IdSwitch == IdSwitch).Count();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MPanels -> CountPanels(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
            return(res);
        }
Exemplo n.º 26
0
        // GetTotalUsers()
        public int GetTotalMembers()
        {
            int res = 0;
            var db  = new PocoDynamo(con.GetClient());

            try
            {
                res = db.ScanAll <Users>().Count();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> GetTotalMembers(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
            return(res);
        }
Exemplo n.º 27
0
        // DeleteUser()
        public void DeleteUser(string UserName)
        {
            var db = new PocoDynamo(con.GetClient());

            db.RegisterTable <Users>();

            try
            {
                db.DeleteItem <Users>(UserName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MUsers -> DeleteUser(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Exemplo n.º 28
0
        // GetPanelInfo()
        public Panels[] GetPanelInfo(string IdPanel)
        {
            var db = new PocoDynamo(con.GetClient());

            Panels[] res = { };

            try
            {
                res = db.ScanAll <Panels>().Where(x => x.IdPanel == IdPanel).ToArray();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MPanels -> GetPanelInfo(). \nDescripción: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
            return(res);
        }
Exemplo n.º 29
0
        public void StoreResponse_WhenAResponsesForARequestAlreadyExists_DoesNotStoreResponseAgain()
        {
            var sut = CreateSut();

            sut.PurgeData <Requests>();
            sut.PurgeData <Responses>();

            var requestId = sut.StoreRequest("/test", HttpMethod.Get, "test".ToAsciiBytes());

            Expression <Func <Request, bool> > expr = r => r.Content.Contains("test");

            sut.StoreResponse(requestId, "test", expr.ToString(), "test".ToAsciiBytes());
            sut.StoreResponse(requestId, "test", expr.ToString(), "test".ToAsciiBytes());

            var dynamo = new PocoDynamo(CreateAmazonDynamoDbClientWithLocalDbInstance());

            dynamo.Scan <Responses>(new ScanRequest("Responses"))
            .Count(responses => responses.RequestId == requestId)
            .Should().Be(1);
        }
Exemplo n.º 30
0
        // AddFile()
        private void AddFile(string IdSwitch, string NewFile, string FileName)
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <Files>();

                var NewFile_ = new Files
                {
                    IdSwitch = IdSwitch,
                    Location = NewFile,
                    FileName = FileName
                };

                db.PutItem(NewFile_);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitchInfo -> GetPanelSwitches(). \nDescripción: " + ex.Message);
            }
        }