Esempio n. 1
0
        public async Task <IActionResult> Register(UserForRegisterDto userForRegisterDto)
        {
            //validate
            var repo = new TableStorageRepository();

            userForRegisterDto.Email = userForRegisterDto.Email.ToLower();

            if (await _repo.UserExists(userForRegisterDto.Email))
            {
                return(BadRequest("Email already exists!"));
            }

            var userToCreate = _mapper.Map <User>(userForRegisterDto);
            var pass         = userForRegisterDto.Password.ToString();


            ////sendgrid
            var CurrentUserId = (User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var userLogged    = await repo.GetUser(CurrentUserId);

            Execute(userLogged, userToCreate, pass).Wait();

            //// end

            var createdUser = await _repo.Register(userToCreate, userForRegisterDto.Password);

            var userToReturn = _mapper.Map <UserDto>(createdUser);


            return(CreatedAtRoute("GetUser", new { controller = "User", id = createdUser.Id }, userToReturn));
        }
Esempio n. 2
0
        public async Task <IActionResult> GetAllUsers([FromQuery] UserParams userParams)
        {
            var repo = new TableStorageRepository();

            var users = await repo.GetUsersWithoutParams();

            var CurrentUserId = (User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var userLogged = await repo.GetUser(CurrentUserId);

            if (userLogged.Role == "admin")
            {
                var usersAdmin = await repo.GetUsersWithoutParamsForAdmin();

                var usersForAdmin = _mapper.Map <IEnumerable <UserDto> >(usersAdmin);

                return(Ok(usersForAdmin));
            }


            if (!string.IsNullOrEmpty(userParams.UserId))
            {
                users = users.Where(x => x.RowKey != userParams.UserId).OrderBy(x => x.Name);
            }

            users = users.OrderBy(x => x.Name);

            var usersToReturn = _mapper.Map <IEnumerable <UserDto> >(users);

            if (!usersToReturn.Any())
            {
                return(NotFound());
            }
            return(Ok(usersToReturn));
        }
Esempio n. 3
0
        public virtual void Add_ValidProjectionView_ProjectionViewCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ThreadedContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger = new ConsoleLogger(new LoggerSettingsConfigurationSection(), correlationIdHelper);
            TableStorageDataStore <TestEvent> dataStore = CreateDataStore <TestEvent>(logger, new ConfigurationManager());

            var event1 = new TestEvent
            {
                Rsn           = Guid.NewGuid(),
                Id            = Guid.NewGuid(),
                CorrelationId = correlationIdHelper.GetCorrelationId(),
                Frameworks    = new List <string> {
                    "Test 1"
                },
                TimeStamp = DateTimeOffset.UtcNow
            };

            // Act
            dataStore.Add(event1);

            // Assert
            var timer      = new Stopwatch();
            var repository = new TableStorageRepository <TestQueryStrategy, TestQueryBuilder <TestEvent>, TestEvent>(() => dataStore, null);

            timer.Start();
            TestEvent view = repository.Load(event1.Rsn);

            timer.Stop();
            Console.WriteLine("Load operation took {0}", timer.Elapsed);
            Assert.IsNotNull(view);
            Assert.AreEqual(event1.Id, view.Id);
        }
Esempio n. 4
0
        public async Task CanQueryWithSingleIntGreaterThan()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            8
                        },
                        Comparison = Comparisons.GreaterThan
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "Level"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(2);
            results.Any(x => x.Id == "7").ShouldBeTrue();
            results.Any(x => x.Id == "8").ShouldBeTrue();
        }
Esempio n. 5
0
        public static async Task <ITableStorageRepository <NotifiedSessionEntity> > GetRepositoryAsync(this NewSessionNotificationConfig config)
        {
            var repo = new TableStorageRepository <NotifiedSessionEntity>(CloudStorageAccount.Parse(config.ConnectionString), config.Table);
            await repo.InitializeAsync();

            return(repo);
        }
Esempio n. 6
0
        public async Task CanQueryWithSingleGuidEquals()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            Guid.Parse("9B522321-B689-43EC-A3DC-DC17EE2A42DD")
                        },
                        Comparison = Comparisons.Equal
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "TypeId"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(2);
            results.Any(x => x.Id == "2").ShouldBe(true);
            results.Any(x => x.Id == "5").ShouldBe(true);
        }
Esempio n. 7
0
        public async Task CanQueryWithSingleDateLessEqualThan()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            new DateTime(2016, 1, 1).ToUtc()
                        },
                        Comparison = Comparisons.LessThan
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "Effective"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(2);
            results.Any(x => x.Id == "4").ShouldBe(true);
            results.Any(x => x.Id == "5").ShouldBe(true);
        }
Esempio n. 8
0
        public async Task CanQueryWithMultipleValueStringsEquals()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            "6", "7", "8"
                        },
                        Comparison = Comparisons.Equal
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "Id"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(3);
            results.Any(x => x.Id == "6").ShouldBeTrue();
            results.Any(x => x.Id == "7").ShouldBeTrue();
            results.Any(x => x.Id == "8").ShouldBeTrue();
        }
Esempio n. 9
0
        public async Task CanQueryWithMultipleValueGuidsEquals()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>
                        {
                            Guid.Parse("DE6EFD89-2D62-4E63-98D2-AEA9E622B223"),
                            Guid.Parse("DC742320-F3A4-4DE1-9239-6A9EC68BD430"),
                            Guid.Parse("CC562BC9-C2E5-46D8-B701-E5D57F5800B8")
                        },
                        Comparison = Comparisons.Equal
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "TypeId"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(3);
            results.Any(x => x.Id == "8").ShouldBeTrue();
            results.Any(x => x.Id == "6").ShouldBeTrue();
            results.Any(x => x.Id == "3").ShouldBeTrue();
        }
Esempio n. 10
0
        public async Task CanHandleEntityTypeWithStringBasedPartition()
        {
            Expression <Func <DocumentDbFoo1, string> > expression = x => x.MyStringCategory;
            var configurations = GetBaseConfigurations <DocumentDbFoo1>((MemberExpression)expression.Body);

            TableStorageRepository.Configure(typeof(DocumentDbFoo1), configurations);

            const string id = "3";

            await TableStorageRepository.AddAsync(new DocumentDbFoo1
            {
                Id               = id,
                Name             = "Foo 1",
                MyStringCategory = "cat 1"
            }, null);

            await TableStorageRepository.UpdateAsync(new DocumentDbFoo1
            {
                Id               = id,
                Name             = "Foo 1 v2",
                MyStringCategory = "cat 1"
            }, null);

            try
            {
                var item = (await GetByIdAsync <DocumentDbFoo1>(id)).Single();

                item.Name.ShouldBe("Foo 1 v2");
            }
            finally
            {
                TableStorageRepository.DeleteAllAsync <DocumentDbFoo1>(null).GetAwaiter().GetResult();
            }
        }
Esempio n. 11
0
        public virtual void Add_ValidProjectionEntityView_ProjectionEntityViewCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ThreadedContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger = new ConsoleLogger(new LoggerSettingsConfigurationSection(), correlationIdHelper);
            TableStorageDataStore <TestEntity> dataStore = CreateDataStore <TestEntity>(logger, new ConfigurationManager());

            var event1 = new TestEntity
            {
                Rsn  = Guid.NewGuid(),
                Name = "Name"
            };

            // Act
            dataStore.Add(event1);

            // Assert
            var timer      = new Stopwatch();
            var repository = new TableStorageRepository <TestQueryStrategy, TestQueryBuilder <TestEntity>, TestEntity>(() => dataStore, null);

            timer.Start();
            TestEntity view = repository.Load(event1.Rsn);

            timer.Stop();
            Console.WriteLine("Load operation took {0}", timer.Elapsed);
            Assert.IsNotNull(view);
            Assert.AreEqual(event1.Rsn, view.Rsn);
            Assert.AreEqual(event1.Name, view.Name);
        }
Esempio n. 12
0
        private static async void SaveUser()
        {
            var r = new TableStorageRepository<User>(new DevelopmentStorageContext(), "Users");

            var user = new User
            {
                PartitionKey = "user",
                RowKey = "steve",
                Name = "Steve Hobbs",
            };

            r.BatchCommitted += (s, a) =>
            {
                Console.WriteLine("Committed..");
            };

            r.Insert(user);
            await r.CommitAsync();

            var user2 = await r.SingleAsync(new TableStorageKey("steve", "user"));

            if (user2 != null)
            {
                Console.WriteLine(user2.Name);
            }

            var users = await r.QueryAsync();
            users.ToList().ForEach(u => Console.WriteLine(u.RowKey));
        }
        public async Task CanQueryWithSingleDateEquals()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            new DateTime(2017, 1, 1).ToUtc()
                        },
                        Comparison = Comparisons.Equal
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "Effective"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(1);
            results[0].Id.ShouldBe("1");

            await RemoveAll();
        }
Esempio n. 14
0
        public static async Task <ITableStorageRepository <Vote> > GetRepositoryAsync(this VotingConfig config)
        {
            var repo = new TableStorageRepository <Vote>(CloudStorageAccount.Parse(config.ConnectionString), config.Table);
            await repo.InitializeAsync();

            return(repo);
        }
Esempio n. 15
0
        public async Task <IActionResult> GetUsers([FromQuery] UserParams userParams)
        {
            var repo = new TableStorageRepository();

            var CurrentUserId = (User.FindFirst(ClaimTypes.NameIdentifier).Value);

            userParams.UserId = CurrentUserId;

            var userLogged = await repo.GetUser(CurrentUserId);

            if (!string.IsNullOrEmpty(userLogged.Role) && userParams.Team)
            {
                userParams.Role = userLogged.Role;
                if (!string.IsNullOrEmpty(userLogged.Manager_ID))
                {
                    userParams.Manager = userLogged.Manager_ID;
                }
            }

            var users = await repo.GetUsers(userParams);

            var usersToReturn = _mapper.Map <IEnumerable <UserDto> >(users);

            Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);

            if (!usersToReturn.Any())
            {
                return(NotFound());
            }
            return(Ok(usersToReturn));
        }
Esempio n. 16
0
        static IRepository <CloudTable> GetRepository(string connectionString)
        {
            var options    = new TableStorageOptions();
            var repository = new TableStorageRepository(connectionString, options);

            return(repository);
        }
Esempio n. 17
0
        public async Task CanQueryWithSingleIntLessEqualThanWithStringEqual()
        {
            await Seed();

            QueryParameter[] args =
            {
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            2
                        },
                        Comparison = Comparisons.LessEqualThan
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "Level"), false)
                },
                new QueryParameter
                {
                    ContextValue = new ContextValue{
                        Values = new List <object>{
                            "Foo 4"
                        },
                        Comparison = Comparisons.Equal
                    },
                    MemberModel = new ModelMember(_type, _accessor,
                                                  _members.Single(x => x.Name == "Name"), false)
                }
            };

            var results = (await TableStorageRepository.QueryAsync <DocumentDbFoo3>("test", args, null, null)).ToList();

            results.Count.ShouldBe(1);
            results[0].Id.ShouldBe("4");
        }
Esempio n. 18
0
        public async Task <IActionResult> GiveFeedback(GiveFeedbackDto giveFeedbackDto)
        {
            var repo         = new TableStorageRepository();
            var userToCreate = _mapper.Map <Feedbacks>(giveFeedbackDto);
            var createdUser  = await repo.GiveFeedback(userToCreate);

            return(Ok(createdUser));
        }
        public void TableStorageRepository_FindByPartition()
        {
            string    tablePrefix      = "TEST" + Guid.NewGuid().ToString("N");
            var       data             = new TableStorageRepository(ConnectionString, tablePrefix);
            string    tableName        = data.GetTable <EsoSale>().Name;
            var       salesByPartition = new Dictionary <int, List <EsoSale> >();
            const int saleCount        = 100;

            try
            {
                for (int i = 0; i < saleCount; i++)
                {
                    // Arrange
                    var sale = CreateRandomSale();
                    data.InsertOrReplace(sale);
                    List <EsoSale> partition;
                    if (!salesByPartition.TryGetValue(sale.TimestampId, out partition))
                    {
                        partition = new List <EsoSale>();
                        salesByPartition.Add(sale.TimestampId, partition);
                    }

                    // Act
                    partition.Add(sale);
                }

                foreach (int timestampId in salesByPartition.Keys)
                {
                    // Arrange
                    List <EsoSale> expectedSales = salesByPartition[timestampId];

                    // Act
                    EsoSale[] partitionSales =
                        data.Find <EsoSale>(timestampId.ToString(CultureInfo.InvariantCulture)).ToArray();

                    // Assert
                    EsoSale missingSale = partitionSales.FirstOrDefault(x => expectedSales.All(y => y.RowKey != x.RowKey));
                    if (missingSale != null)
                    {
                        Assert.Fail("Table {0} Partition {1} missing expected entity with row key {2}", tableName,
                                    missingSale.PartitionKey,
                                    missingSale.RowKey);
                    }
                    EsoSale extraSale = expectedSales.FirstOrDefault(x => partitionSales.All(y => y.RowKey != x.RowKey));
                    if (extraSale != null)
                    {
                        Assert.Fail("Table {0} Partition {1} contains unexpected entity with row key {2}", tableName,
                                    extraSale.PartitionKey,
                                    extraSale.RowKey);
                    }
                }
            }
            finally
            {
                // Clean up
                data.RemoveTable <EsoSale>();
            }
        }
Esempio n. 20
0
        public void InitializeNewQuery_Should_CreateNewTableQuery()
        {
            var mockContext = new StorageContextMockFactory().CreateStorageContextMock();
            var provider    = new TableStorageUnitOfWorkProvider(uowRegistry, () => mockContext.Object);
            var repository  = new TableStorageRepository <Musician>(provider, new LocalDateTimeProvider());
            var query       = repository.InitializeNewQuery();

            Assert.NotNull(query);
        }
Esempio n. 21
0
        public async Task <IActionResult> SoftDeleteAdmin(UserDto userDto)
        {
            var repo  = new TableStorageRepository();
            var cards = await repo.GetUser(userDto.ID);

            _mapper.Map(userDto, cards);
            await repo.PostEntityUser(cards);

            return(Ok());
        }
Esempio n. 22
0
        public void InitializeNew_Should_SetPartitionKeyAndRowKey()
        {
            var mockContext = new StorageContextMockFactory().CreateStorageContextMock();
            var provider    = new TableStorageUnitOfWorkProvider(uowRegistry, () => mockContext.Object);
            var repository  = new TableStorageRepository <Musician>(provider, new LocalDateTimeProvider());
            var employee    = repository.InitializeNew("Doe", "*****@*****.**");

            Assert.Equal("Doe", employee.PartitionKey);
            Assert.Equal("*****@*****.**", employee.RowKey);
        }
Esempio n. 23
0
        public async Task <IActionResult> UpdateUser(string id, UpdateUserDto requestUpdate)
        {
            var repo  = new TableStorageRepository();
            var cards = await repo.GetUser(id);

            _mapper.Map(requestUpdate, cards);
            await repo.PostEntityUser(cards);

            return(Ok());
        }
Esempio n. 24
0
        public CustomControllerCache()
        {
            UnitOfWork           = new UnitOfWorkCQRS(new EscarGoContext());
            QueueRepositoryAsync = new QueueRepositoryAsync();
            ITableStorageRepository tablestorageRepository = new TableStorageRepository();
            IRedisRepository        redisRepository        = new RedisRepository(tablestorageRepository);

            Builder            = new ViewModelBuilderQueue(UnitOfWork, redisRepository);
            TicketModelBuilder = new TicketModelBuilderCache(UnitOfWork, QueueRepositoryAsync);
        }
Esempio n. 25
0
        public TableStorageRepositoryQueryTests()
        {
            Expression <Func <DocumentDbFoo3, string> > expression = x => x.Category;
            var configurations = GetBaseConfigurations <DocumentDbFoo3>((MemberExpression)expression.Body);

            TableStorageRepository.Configure(typeof(DocumentDbFoo3), configurations);

            _accessor = TypeAccessor.Create(_type);
            _members  = _accessor.GetMembers();
        }
        public override void Given()
        {
            this.TableStorageContext = new Mock<ITableStorageContext> { DefaultValue = DefaultValue.Mock };
            var userConfiguration = new UserConfiguration { UserId = TestValues.USER_ID };
            this.TableStorageContext
                .Setup(x => x.UserConfigurations.GetByNameIdentifier())
                .Returns(userConfiguration);

            this.TableStorageRepository = new TableStorageRepository<Card>(this.TableStorageContext.Object);
        }
 protected TableStorageRepositoryTestsBase()
 {
     TableStorageRepository = new TableStorageRepository(Extensions.GetLogger <TableStorageRepository>(), new List <ITableStorageComparison>
     {
         new TableStorageComparisonBool(),
         new TableStorageComparisonInt(),
         new TableStorageComparisonString(),
         new TableStorageComparisonDate(),
         new TableStorageComparisonGuid()
     });
 }
Esempio n. 28
0
        public async Task <IActionResult> RequestFeedback(RequestFeedbackDto requestFeedbackDto, string id)
        {
            //validate
            var repo = new TableStorageRepository();

            var requestToCreate = _mapper.Map <Feedbacks>(requestFeedbackDto);

            var createdRequest = await repo.RequestFeedback(requestToCreate, id);

            return(Ok(createdRequest));
        }
Esempio n. 29
0
        private static async Task <(ITableStorageRepository <SessionEntity>, ITableStorageRepository <PresenterEntity>)> GetSessionRepositoryAsync(string connectionString, string sessionsTable, string presentersTable)
        {
            var storageAccount = CloudStorageAccount.Parse(connectionString);
            var sessionsRepo   = new TableStorageRepository <SessionEntity>(storageAccount, sessionsTable);
            var presentersRepo = new TableStorageRepository <PresenterEntity>(storageAccount, presentersTable);
            await sessionsRepo.InitializeAsync();

            await presentersRepo.InitializeAsync();

            return(sessionsRepo, presentersRepo);
        }
Esempio n. 30
0
        public static async Task <(ITableStorageRepository <ConferenceFeedbackEntity>, ITableStorageRepository <SessionFeedbackEntity>)> GetRepositoryAsync(this FeedbackConfig feedback)
        {
            var storageAccount = CloudStorageAccount.Parse(feedback.ConnectionString);
            var conferenceFeedbackRepository = new TableStorageRepository <ConferenceFeedbackEntity>(storageAccount, feedback.ConferenceFeedbackTable);
            var sessionFeedbackRepository    = new TableStorageRepository <SessionFeedbackEntity>(storageAccount, feedback.SessionFeedbackTable);
            await conferenceFeedbackRepository.InitializeAsync();

            await sessionFeedbackRepository.InitializeAsync();

            return(conferenceFeedbackRepository, sessionFeedbackRepository);
        }
 protected TableStorageRepositoryTestsBase()
 {
     TableStorageRepository = new TableStorageRepository(Substitute.For <ILogger>(), new List <ITableStorageComparison>
     {
         new TableStorageComparisonBool(),
         new TableStorageComparisonInt(),
         new TableStorageComparisonString(),
         new TableStorageComparisonDate(),
         new TableStorageComparisonGuid()
     });
 }
        public static async void Run([QueueTrigger("delete-posts-from-track", Connection = "QUEUESTORAGE_CONNECTION")] CloudQueueMessage trackId, TraceWriter log)
        {
            List <string> listOfPostsToDelete = await PostRepository.GetPostIdsInTrack(trackId.AsString);

            foreach (var postId in listOfPostsToDelete)
            {
                TableStorageRepository.AddMessageToQueue("process-delete-post", $"{trackId.AsString}.{postId}");
            }

            log.Info($"Added all posts in track to delete queue: {trackId.AsString}");
        }
Esempio n. 33
0
        public static void Main()
        {
            ITableStorageRepository<Person> personRespository = new TableStorageRepository<Person>();

            Person userToStore = new Person
            {
                Id = 1,
                Name = "Chetan",
                PartitionKey = "Person",
                RowKey = string.Format("{0}-{1}", 1, "Chetan"),
            };

            personRespository.CreateTable();
            personRespository.Put(userToStore);

            var retrievedUser = personRespository.Get(userToStore.RowKey);
        }
 public override void Given()
 {
     this.TableStorageContext = new Mock<ITableStorageContext> { DefaultValue = DefaultValue.Mock };
     this.TableStorageRepository = new TableStorageRepository<UserConfiguration>(this.TableStorageContext.Object);
 }