public void GetPersonNoTracking_ReturnsThePersonWithTheGivenId() { // Arrange // first create the collection of data. It no longer has to be an IQueryable var data = new List <Person> { new Person { Id = 1, FirstName = "BBB" }, new Person { Id = 2, FirstName = "ZZZ" }, new Person { Id = 3, FirstName = "AAA" }, }; // create the mock DbSet using the helper method var mockSet = NSubstituteUtils.CreateMockDbSet(data); // do the wiring between DbContext and DbSet var mockContext = Substitute.For <IPeopleDbContext>(); mockContext.People.Returns(mockSet); var service = new PeopleService(mockContext); // Act var secondPerson = service.GetPersonNoTracking(2); // Assert Assert.That(secondPerson.Id, Is.EqualTo(2)); Assert.That(secondPerson.FirstName, Is.EqualTo("ZZZ")); }
private void PeopleTable_ItemCommand(object source, RepeaterCommandEventArgs e) { var serv = new PeopleService(); switch (e.CommandName) { case "update": var updatedPeople = serv.GetPeople(Convert.ToInt32(e.CommandArgument)); NameBox.Text = Convert.ToString(updatedPeople.Name); HeightBox.Text = Convert.ToString(updatedPeople.Height); WeightBox.Text = Convert.ToString(updatedPeople.Weight); IdBox.Text = Convert.ToString(updatedPeople.Id); break; case "delete": serv.DelPeople(Convert.ToInt32(e.CommandArgument)); break; default: break; } //Refresh data PeopleTable.DataSource = serv.GetPeoples(); PeopleTable.DataBind(); }
public static Person ShowPeopleFound(string name) { PeopleFound peopleFound = PeopleService.GetPersonByName(name); if (peopleFound.Status == false) { throw new Exception(peopleFound.Message); } int contador = 1; foreach (var person in peopleFound.People) { Console.WriteLine($"{contador} - {person.FullName}"); contador++; } int option = int.Parse(ReadString("Escolha uma pessoa: ")); if (option <1 | option> peopleFound.People.Count) { Console.WriteLine("Opção Inválida"); MainMenu(); } return(peopleFound.People[option - 1]); }
public void SortPeopleTest() { PeopleService peopleService = new PeopleService(); var people = new List <IPerson>(); people.Add(new Person() { Address = "16 People Place", Firstname = "John", Lastname = "Doe", PhoneNumber = "0123456789" }); people.Add(new Person() { Address = "106 Italy Street", Firstname = "Jane", Lastname = "Doe", PhoneNumber = "0123456789" }); var expected = new Dictionary <string, int>(); expected.Add("Doe", 2); expected.Add("Jane", 1); expected.Add("John", 1); var result = peopleService.GetOccurences(people); Assert.IsNotNull(result); Assert.AreEqual(expected["Doe"], result["Doe"]); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var personid = Convert.ToInt32(Request.QueryString["ID"]); PeopleService service = new PeopleService(); Contoso.Model.People person = service.GetPersonById(personid); txtFirstName.Text = person.FirstName; txtLastName.Text = person.LastName; txtAge.Text = person.Age.ToString(); txtEmail.Text = person.Email; TxtPhone.Text = person.Phone.ToString(); txtAddress1.Text = person.AddressLine1; txtUnit.Text = person.UnitOrApartmentNumber.ToString(); txtCity.Text = person.City; txtZipcode.Text = person.ZipCode.ToString(); ddlStates.SelectedValue = person.State; ddlStates.DataSource = Utility.GetAllStates(); ddlStates.DataTextField = "StateName"; ddlStates.DataValueField = "Value"; ddlStates.DataBind(); } }
public async Task ListAsync_Success() { var connection = await GetOpenSqliteConnectionAsync(); try { var options = new DbContextOptionsBuilder <PeopleContext>() .UseSqlite(connection) .Options; await SeedDataAsync(options); using (var context = new PeopleContext(options)) { var service = new PeopleService(context); var people = await service.ListAsync(); people.Should().NotBeNullOrEmpty(); people.Should().HaveCount(5); } } finally { connection.Close(); } }
public async Task Delete_NegativeId_Failure() { var connection = await GetOpenSqliteConnectionAsync(); try { var options = new DbContextOptionsBuilder <PeopleContext>() .UseSqlite(connection) .Options; await SeedDataAsync(options); using (var context = new PeopleContext(options)) { var service = new PeopleService(context); Func <Task> func = () => service.DeleteAsync(-1); func.Should().Throw <ArgumentException>(); } } finally { connection.Close(); } }
public void TestCreateMethod_CreateFourPeoples() { // Arrange People inputPeople1 = new People(); inputPeople1.FirstName = "Harry"; inputPeople1.LastName = "Porter"; inputPeople1.Address = Constant.Constant.Address; inputPeople1.Gender = Constant.Constant.Gender; inputPeople1.Interests = Constant.Constant.Interests; inputPeople1.DateOfBirth = DateTime.Now; People inputPeople2 = new People(); inputPeople2.FirstName = "Harriet"; inputPeople2.LastName = "Huang"; inputPeople2.Address = Constant.Constant.Address; inputPeople2.Gender = Constant.Constant.Gender; inputPeople2.Interests = Constant.Constant.Interests; inputPeople2.DateOfBirth = DateTime.Now; People inputPeople3 = new People(); inputPeople3.FirstName = "Hunter"; inputPeople3.LastName = "Yin"; inputPeople3.Address = Constant.Constant.Address; inputPeople3.Gender = Constant.Constant.Gender; inputPeople3.Interests = Constant.Constant.Interests; inputPeople3.DateOfBirth = DateTime.Now; People inputPeople4 = new People(); inputPeople4.FirstName = "Peter"; inputPeople4.LastName = "P."; inputPeople4.Address = Constant.Constant.Address; inputPeople4.Gender = Constant.Constant.Gender; inputPeople4.Interests = Constant.Constant.Interests; inputPeople4.DateOfBirth = DateTime.Now; var mockSet = new Mock <DbSet <People> >(); var mockContext = new Mock <PeopleContext>(); mockContext.Setup(m => m.Peoples).Returns(mockSet.Object); // Act var service = new PeopleService(mockContext.Object); service.Create(inputPeople1); service.Create(inputPeople2); service.Create(inputPeople3); service.Create(inputPeople4); // Assert mockSet.Verify(m => m.Add(It.IsAny <People>()), Times.AtLeast(4)); mockContext.Verify(m => m.SaveChanges(), Times.AtLeast(4)); }
public async Task If_The_Data_Conversion_Encounters_an_Error_Must_Return_Failure() { // // Arrange // var mockedApiClient = new Mock <IPeopleAreUsHttpClient>(); mockedApiClient.Setup(x => x.GetPeopleAsync()).ReturnsAsync(OperationResult <List <Person> > .Success(new List <Person> { new Person { Name = "some name", Age = 18, Gender = "blah", Pets = new List <Pet>() } })); var mockedMapper = new Mock <IMapper <Person, Domain.Models.Person> >(); mockedMapper.Setup(x => x.Map(It.IsAny <Person>())).Throws <Exception>(); var service = new PeopleService(mockedApiClient.Object, Mock.Of <IPetTypeSpecification>(), mockedMapper.Object, Mock.Of <ILogger <PeopleService> >()); // // Act // var operation = await service.GetPetOwnersAsync(It.IsAny <GetPetOwnersRequest>()); // // Assert // Assert.False(operation.Status); }
public void TestCreateMethod_PeopleWithImage() { // Arrange People inputPeople = new People(); inputPeople.FirstName = Constant.Constant.Firstname; inputPeople.LastName = Constant.Constant.LastName; inputPeople.Address = Constant.Constant.Address; inputPeople.Gender = Constant.Constant.Gender; inputPeople.Interests = Constant.Constant.Interests; inputPeople.DateOfBirth = DateTime.Now; Image img = System.Drawing.Image.FromFile("../../Content/Images/HarryPotter.jpg"); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); inputPeople.Image = ms.ToArray(); var mockSet = new Mock <DbSet <People> >(); var mockContext = new Mock <PeopleContext>(); mockContext.Setup(m => m.Peoples).Returns(mockSet.Object); // Act var service = new PeopleService(mockContext.Object); service.Create(inputPeople); // Assert mockSet.Verify(m => m.Add(It.IsAny <People>()), Times.Once()); mockContext.Verify(m => m.SaveChanges(), Times.Once()); }
public void TestCreateMethod_PeopleWithEmptyInformation() { // Arrange People inputPeople = new People(); inputPeople.FirstName = string.Empty; inputPeople.LastName = string.Empty; inputPeople.Address = string.Empty; inputPeople.Gender = string.Empty; inputPeople.Interests = string.Empty; inputPeople.DateOfBirth = DateTime.Now; inputPeople.Image = null; var mockSet = new Mock <DbSet <People> >(); var mockContext = new Mock <PeopleContext>(); mockContext.Setup(m => m.Peoples).Returns(mockSet.Object); // Act var service = new PeopleService(mockContext.Object); service.Create(inputPeople); // Assert mockSet.Verify(m => m.Add(It.IsAny <People>()), Times.Never()); mockContext.Verify(m => m.SaveChanges(), Times.Never()); }
public void TestCreateMethod_PeopleWithoutImage() { // Arrange People inputPeople = new People(); inputPeople.FirstName = Constant.Constant.Firstname; inputPeople.LastName = Constant.Constant.LastName; inputPeople.Address = Constant.Constant.Address; inputPeople.Gender = Constant.Constant.Gender; inputPeople.Interests = Constant.Constant.Interests; inputPeople.DateOfBirth = DateTime.Now; var mockSet = new Mock <DbSet <People> >(); var mockContext = new Mock <PeopleContext>(); mockContext.Setup(m => m.Peoples).Returns(mockSet.Object); // Act var service = new PeopleService(mockContext.Object); service.Create(inputPeople); // Assert mockSet.Verify(m => m.Add(It.IsAny <People>()), Times.Once()); mockContext.Verify(m => m.SaveChanges(), Times.Once()); }
public async Task TestSearchMethodWithSearchString() { var data = new List <People> { new People { FirstName = "Hellen", LastName = "Wang" }, new People { FirstName = "Erin", LastName = "Zhang" }, new People { FirstName = "Lin", LastName = "Wang" }, }.AsQueryable(); var mockSet = new Mock <DbSet <People> >(); mockSet.As <IQueryable <People> >().Setup(m => m.Provider).Returns(data.Provider); mockSet.As <IQueryable <People> >().Setup(m => m.Expression).Returns(data.Expression); mockSet.As <IQueryable <People> >().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As <IQueryable <People> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock <PeopleContext>(); mockContext.Setup(c => c.Peoples).Returns(mockSet.Object); var service = new PeopleService(mockContext.Object); List <People> searchresults = await service.Search("a"); Assert.AreEqual(3, searchresults.Count()); Assert.AreEqual("Hellen", searchresults[0].FirstName); Assert.AreEqual("Erin", searchresults[1].FirstName); Assert.AreEqual("Lin", searchresults[2].FirstName); }
public static void ToJson() { var json = JsonConvert.SerializeObject(PeopleService.Read(), settings); var saveFileDialog = new SaveFileDialog() { FileName = "people.json", Filter = "Json files|*.json|All files|*.*" }; if (saveFileDialog.ShowDialog() == true) { File.WriteAllText(saveFileDialog.FileName, json); /*using (var file = new FileStream(saveFileDialog.FileName, FileMode.Create)) * { * using (var streamWriter = new StreamWriter(file)) * { * streamWriter.Write(json); * } * }*/ } WriteLine(json); Console.ReadLine(); }
public void SelectAll_Test() { PeopleService svc = new PeopleService(); List <People> result = svc.GetAll(); Assert.IsTrue(result.Count > 0, "Select All has failed"); }
protected override async Task OnAfterRenderAsync(bool firstRender) { if (_loaded) { return; } _loaded = true; _creating = NavigationManager.ToBaseRelativePath(NavigationManager.Uri).ToLowerInvariant(). StartsWith("admin/document_people/create", StringComparison.InvariantCulture); if (Id <= 0 && !_creating) { return; } _people = await PeopleService.GetAsync(); _model = _creating ? new DocumentPersonViewModel() : await Service.GetAsync(Id); _authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); _editing = _creating || NavigationManager.ToBaseRelativePath(NavigationManager.Uri).ToLowerInvariant(). StartsWith("admin/document_people/edit/", StringComparison.InvariantCulture); if (_editing) { SetCheckboxes(); } StateHasChanged(); }
public static PeopleData GetPeopleData(DateTime fromDate, DateTime toDate) { var peopleData = new PeopleData { MostActiveDateRange = new List <PeopleDataByWeek>() }; var yearAndWeekNumbers = GetYearAndWeekNumbers(fromDate, toDate); foreach (var yearAndWeekNumber in yearAndWeekNumbers) { var weekStartDate = GetDateRangeFromWeekNumber(yearAndWeekNumber.Year, yearAndWeekNumber.WeekNumber); var weekEndDate = weekStartDate.AddDays(7); var peopleService = new PeopleService(); var topPeople = peopleService.GetMostActiveDateRange(weekStartDate, weekEndDate); var peopleDataByWeek = new PeopleDataByWeek { WeekNumber = yearAndWeekNumber.WeekNumber, Year = yearAndWeekNumber.Year, MostActive = topPeople }; peopleData.MostActiveDateRange.Add(peopleDataByWeek); } return(peopleData); }
// GET: People public ActionResult ListPeople() { PeopleService peopleService = new PeopleService(); List <People> list = peopleService.GetAllPeople(); return(View(list)); }
public async Task GetAsync_Id_CorrectPerson() { var id = 2; var connection = await GetOpenSqliteConnectionAsync(); try { var options = new DbContextOptionsBuilder <PeopleContext>() .UseSqlite(connection) .Options; await SeedDataAsync(options); using (var context = new PeopleContext(options)) { var service = new PeopleService(context); var person = await service.GetAsync(id); person.Should().NotBeNull(); person.Id.Should().Be(id); } } finally { connection.Close(); } }
public ActionResult DeletePeople(People person) { PeopleService peopleService = new PeopleService(); peopleService.DeletePeople(person.ID); return(RedirectToAction("ListPeople")); }
public PeopleController(IConfiguration config, PeopleService people, ConstantsReaderService constantsReader) { configuration = config; peopleService = people; constantsReaderService = constantsReader; constants = constantsReaderService.ReadConstants(); }
public ActionResult AddPeople(People person) { PeopleService peopleService = new PeopleService(); peopleService.AddPeople(person); return(RedirectToAction("ListPeople")); }
public void SortAddresses() { PeopleService peopleService = new PeopleService(); var people = new List <IPerson>(); people.Add(new Person() { Address = "16 People Place", Firstname = "John", Lastname = "Doe", PhoneNumber = "0123456789" }); people.Add(new Person() { Address = "106 Italy Street", Firstname = "Jane", Lastname = "Doe", PhoneNumber = "0123456789" }); var expected = new List <IPerson>(); expected.Add(new Person() { Address = "106 Italy Street", Firstname = "Jane", Lastname = "Doe", PhoneNumber = "0123456789" }); var addresses = peopleService.GetSortedAddresses(people); Assert.IsNotNull(addresses); Assert.AreEqual(expected[0].Address, addresses[0]); }
public ActionResult DetailsPeople(int ID) { PeopleService peopleService = new PeopleService(); var person = peopleService.GetOnePeople(ID); return(View(person)); }
public async Task TestService_OnErrorFromServer_ShouldThrowException() { var httpMessageHandler = new Mock <HttpMessageHandler>(); httpMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ).ThrowsAsync(new Exception("Error")); var logger = Mock.Of <ILogger <PeopleService> >(); var httpClient = new HttpClient(httpMessageHandler.Object); httpClient.BaseAddress = new Uri("http://test/"); var appSettings = new AppSettings(); appSettings.PeopleServiceClientConfig = new PeopleServiceClientConfig() { Url = "http://test/", Endpoint = "endpoint" }; var peopleService = new PeopleService(httpClient, appSettings, logger); try { await peopleService.FetchAllAsync(); Assert.Fail(); } catch (Exception ex) { Assert.AreEqual("Error", ex.Message); } }
public PeopleServiceTests() { _peopleRepo = Substitute.For <IPeopleRepo>(); _placeRepo = Substitute.For <IPlaceRepo>(); _peopleService = new PeopleService(_peopleRepo, _placeRepo); }
public static void EditPerson() { try { string name = ReadString("Digite o nome da pessoa que deseja pesquisar: "); Person chosenPerson = ShowPeopleFound(name); string firstName = ReadString("Digite o nome: ");; string lastName = ReadString("Digite o sobrenome: "); string birthday = ReadString("Digite o aniversário no formato (MM/dd/yyyy): "); while (ValidateDate(birthday) == false) { Console.WriteLine("Data inserida incorretamente!"); birthday = ReadString("Digite o aniversário no formato (MM/dd/yyyy): "); } PeopleService.DeleteOne(chosenPerson.Id); PeopleService.AddNewPerson(firstName, lastName, birthday); EndMethod("Pessoa editada com sucesso!"); } catch (Exception exception) { EndMethod(exception.Message); } }
private void btnAuth_Click(object sender, EventArgs e) { lblStatus.Text = "Authenticating..."; // Create OAuth credential. UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "425537419269-36uofj9uv00ru9qp9653l3u8o2vjvqhn.apps.googleusercontent.com", ClientSecret = "9ur93YzU8rLlAETexFE4KvuW" }, new[] { "email", "profile", "https://www.googleapis.com/auth/contacts.readonly" }, "me", CancellationToken.None).Result; // Create the service. peopleService = new PeopleService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GoogleContactExport", }); lblStatus.Text = "Authenticated!"; btnGetContacts.Enabled = true; btnRemoveAuth.Enabled = true; btnAuth.Enabled = false; //PeopleResource.GetRequest peopleRequest = peopleService.People.Get("people/me"); //peopleRequest.RequestMaskIncludeField = "person.emailAddresses"; //Person profile = peopleRequest.Execute(); //lblStatus.Text = "Authenticated as: " + profile.EmailAddresses[0].Value; }
public static PeopleService GetServiceClient(GoogleClient config, string token) { GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = config.ClientId, ClientSecret = config.ClientSecret, }, Scopes = config.Scopes, DataStore = new FileDataStore("Store"), }); TokenResponse tokenRes = new TokenResponse { AccessToken = token, ExpiresInSeconds = 3600, IssuedUtc = DateTime.UtcNow, }; UserCredential credential = new UserCredential(flow, Environment.UserName, tokenRes); var service = new PeopleService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = config.ApplicationName, }); return(service); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var PersonId = Request.QueryString["ID"]; PeopleService peopleService = new PeopleService(); Contso.Model.People people = peopleService.GetById(Convert.ToInt32(PersonId)); LblId.Text = people.id.ToString(); LblLastName.Text = people.LastName; LblFirstName.Text = people.FirstName; LblMiddleName.Text = people.MiddleName; LblAge.Text = people.Age.ToString(); LblEmail.Text = people.Email; LblPhone.Text = people.Phone; LblAddressLine1.Text = people.AddressLine1; LblAddressLine2.Text = people.AddressLine2; LblUnitOrApartmentNumber.Text = people.UnitOrApartmentNumber; LblCity.Text = people.City; LblState.Text = people.State; LblZipcode.Text = people.Zipcode; LblCreatedDate.Text = people.CreatedDate.ToString(); LblCreatedBy.Text = people.CreatedBy; LblUpdatedDate.Text = people.UpdatedDate.ToString(); LblUpdatedBy.Text = people.UpdatedBy; LblSalt.Text = people.Salt; LblIsLocked.Text = people.IsLocked; LblLastLockedDateTime.Text = people.LastLockedDateTime.ToString(); LblFailedAttempts.Text = people.FailedAttempts.ToString(); } }