예제 #1
0
        public async Task <PhoneBookEntry> EditPhonebookEntryAsync(PhoneBookEntry EditedPhoneBookEntry)
        {
            var phoneBookEntry = await GetPhonebookEntryByIDAsync(EditedPhoneBookEntry.Id);

            if (phoneBookEntry == null)
            {
                return(null);
            }
            else
            {
                try
                {
                    phoneBookEntry.Name        = EditedPhoneBookEntry.Name;
                    phoneBookEntry.PhoneNumber = EditedPhoneBookEntry.PhoneNumber;
                    await Uow.SaveChangesAsync();

                    return(phoneBookEntry);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(null);
                }
            }
        }
        public async Task <PhoneBookEntry> AddPhoneBookEntryAsync(string name, string phoneNumber, int phoneBookId)
        {
            var phoneBook = await phoneBookService.GetPhoneBookByIdAsync(phoneBookId);

            if (phoneBook == null)
            {
                //should define custom exceptions
                throw new Exception("Phone book not found");
            }

            var phoneBookEntry = await GetPhoneBookEntryByNumberAsync(phoneNumber);

            //check if number already exists
            if (phoneBookEntry == null)
            {
                phoneBookEntry = new PhoneBookEntry
                {
                    Name        = name,
                    PhoneNumber = phoneNumber,
                    PhoneBookId = phoneBookId
                };

                await _phoneBookEntryRepository.AddAsync(phoneBookEntry);
            }

            await _phoneBookEntryRepository.SaveChangesAsync();

            // Logic on what to do if number already exists.
            //add custom response
            return(phoneBookEntry);
        }
예제 #3
0
        public async Task <PhoneBookEntry> CreatePhonebookEntryAsync(int PhoneBookID, string Name, string PhoneNumber)
        {
            var phoneBook = await GetPhoneBookByIDAsync(PhoneBookID);

            if (phoneBook == null)
            {
                return(null);
            }
            else
            {
                try
                {
                    var phoneBookEntry = new PhoneBookEntry()
                    {
                        Name = Name, PhoneNumber = PhoneNumber, PhoneBookId = PhoneBookID
                    };
                    PhoneDB.Add(phoneBookEntry);
                    await Uow.SaveChangesAsync();

                    return(phoneBookEntry);
                } catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(null);
                }
            }
        }
예제 #4
0
        public async Task <ActionResult> DeletePhoneBookEntry(Guid phoneBookId, Guid id)
        {
            // Check if phone book exists
            if (!await _phoneBookRepository.ExistsAsync(phoneBookId).ConfigureAwait(false))
            {
                return(NotFound());
            }

            // Check if phone book entry exists
            PhoneBookEntry phoneBookEntry = await _phoneBookEntryRepository.GetPhoneBookEntryWithPhoneBook(id);

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

            // Check if the phone book belongs to the current user
            Guid userId = Guid.Parse(_userInfoService.UserId);

            if (phoneBookEntry.PhoneBook.UserId == userId)
            {
                _phoneBookEntryRepository.Delete(phoneBookEntry);
                await _phoneBookEntryRepository.SaveChangesAsync();

                return(NoContent());
            }

            _logger.LogWarning("User with id {ForbiddenUser} attempted to delete a phone book entry from a phone book owned by {OwningUser}",
                               userId, phoneBookEntry.PhoneBook.UserId);

            // the phone book does not belong to the user
            // forbidden request
            return(Forbid());
        }
예제 #5
0
        public async Task <int> Put(PhoneBookEntry entity)
        {
            var phonebookentry = await _context.PhoneBookEntries.FindAsync(entity.Id);

            _context.Entry(phonebookentry).CurrentValues.SetValues(entity);
            return(1);
        }
예제 #6
0
        public void Run(params string[] args)
        {
            Tenant t = PhoneSystem.Root.GetTenants()[0];
            DN     e = null;

            foreach (DN dn in t.GetDN())
            {
                if (dn.Number == "108")
                {
                    e = dn;
                }
            }
            PhoneBookEntry a = t.CreatePhoneBookEntry();

            a.FirstName   = "TenantFN";
            a.LastName    = "TenantLN";
            a.PhoneNumber = "54321";
            a.Save();
            a             = e.CreatePhoneBookEntry();
            a.FirstName   = "ExtFN";
            a.LastName    = "ExtLN";
            a.PhoneNumber = "7890";
            a.Save();
            Thread.Sleep(2000);
            t.Refresh();
            e.Refresh();
            foreach (PhoneBookEntry pbe in t.GetPhoneBookEntries())
            {
                System.Console.WriteLine(pbe.ToString());
            }
            foreach (PhoneBookEntry pbe in e.GetPhoneBookEntries())
            {
                System.Console.WriteLine(pbe.ToString());
            }
        }
        private List <PhoneBookEntry> phoneList = new List <PhoneBookEntry>(); // Field to hold a list of PhoneBookEntry objects.
        private void ReadFile()
        {
            try
            {
                StreamReader inputFile;                                 // To read the file
                string       line;                                      // To hold a line from the file

                PhoneBookEntry entry = new PhoneBookEntry();            // Create an instance of the PhoneBookEntry structure.

                char[] delim = { ' ', ',', '-' };                       // Create a delimiter array.

                inputFile = File.OpenText("PhoneList.txt");             // Open the PhoneList file.

                while (!inputFile.EndOfStream)                          // Read the lines from the file.
                {
                    line = inputFile.ReadLine();                        // Read a line from the file.
                    string[] tokens = line.Split(delim);                // Tokenize the line
                    entry.Fname  = tokens[0];
                    entry.Lname  = tokens[1];                           // Store the tokens in the entry object.
                    entry.phone3 = tokens[2];
                    entry.phone4 = tokens[3];
                    entry.email  = tokens[4];

                    phoneList.Add(entry);                               // Add the entry object to the List.
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);                            // Display an error message.
            }
        }
예제 #8
0
        public async Task <ActionResult <IEnumerable <PhoneBookEntryResponse> > > GetPhoneBookEntry(Guid phoneBookId, Guid id)
        {
            // Check if phone book exists
            if (!await _phoneBookRepository.ExistsAsync(phoneBookId))
            {
                return(NotFound());
            }

            // Check if phone book entry exists
            PhoneBookEntry phoneBookEntry = await _phoneBookEntryRepository.GetPhoneBookEntryWithPhoneBook(id);

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

            // Check if the phone book belongs to the current user
            Guid userId = Guid.Parse(_userInfoService.UserId);

            if (phoneBookEntry.PhoneBook.UserId == userId)
            {
                return(Ok(_mapper.Map <PhoneBookEntryResponse>(phoneBookEntry)));
            }

            _logger.LogWarning("User with id {ForbiddenUser} attempted to request a phone book entry from a phone book owned by {OwningUser}",
                               userId, phoneBookEntry.PhoneBook.UserId);

            // phone book does not belong to the user
            // forbidden request
            return(Forbid());
        }
예제 #9
0
        public async Task <ActionResult <PhoneBookEntryResponse> > CreatePhoneBookEntry(Guid phoneBookId,
                                                                                        [FromBody] PhoneBookEntryCreateRequest phoneBookEntryCreateRequest)
        {
            // Check if phone book exists
            PhoneBook phoneBook = await _phoneBookRepository.GetByIdAsync(phoneBookId);

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

            // Check if the phone book belongs to the current user
            Guid userId = Guid.Parse(_userInfoService.UserId);

            if (phoneBook.UserId == userId)
            {
                PhoneBookEntry phoneBookEntry = _mapper.Map <PhoneBookEntry>(phoneBookEntryCreateRequest);

                phoneBookEntry = await _phoneBookEntryRepository
                                 .CreatePhoneBookEntryForBook(phoneBookId, phoneBookEntry);

                await _phoneBookRepository.SaveChangesAsync();

                return(CreatedAtRoute("GetPhoneBookEntry", new { phonebookId = phoneBook.Id, id = phoneBookEntry.Id },
                                      _mapper.Map <PhoneBookEntryResponse>(phoneBookEntry)));
            }

            _logger.LogWarning("User with id {ForbiddenUser} attempted to request add a phonebook entry to a phone book owned by {OwningUser}",
                               userId, phoneBook.UserId);

            // the phone book does not belong to the user
            // forbidden request
            return(Forbid());
        }
        public async Task TestMissingRequiredNameShouldThrowException()
        {
            var phonebookentry = new PhoneBookEntry();
            await _phoneBookEntryRepo.Post(phonebookentry);

            Assert.Throws <DbUpdateException>(() => dbContext.SaveChanges());
        }
예제 #11
0
        public IHttpActionResult PutPhoneBookEntry(int id, PhoneBookEntry phoneBookEntry)
        {
            if (id != phoneBookEntry.Id)
            {
                return(BadRequest());
            }

            db.Entry(phoneBookEntry).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PhoneBookEntryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #12
0
        public ActionResult DeleteConfirmed(int id)
        {
            PhoneBookEntry phoneBookEntry = db.PhoneBookEntries.Find(id);

            db.PhoneBookEntries.Remove(phoneBookEntry);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #13
0
 public void Post(PhoneBookEntry phoneBookEntry)
 {
     using (var db = new LiteDatabase(@"Phonebook.db"))
     {
         var users = db.GetCollection <PhoneBookEntry>("phonebookentries");
         users.Insert(phoneBookEntry);
         users.EnsureIndex(x => x.Name);
     };
 }
        public async Task <bool> CreateEntry(string token, PhoneBookEntry entry)
        {
            var result = await BaseURL
                         .AppendPathSegment("phonebook/create")
                         .WithOAuthBearerToken(token)
                         .PostJsonAsync(entry);

            return(result.IsSuccessStatusCode);
        }
예제 #15
0
        private PhoneBookEntry AddPhoneBookEntry()
        {
            phoneBookEntry.PhoneBookId = previousStateResult.AdditionalData.PhoneBookId;
            var content = CreateHttpContent(phoneBookEntry);

            var request = client.PostAsync(action, content);

            phoneBookEntry = Deserialize <PhoneBookEntry>(request.Result.Content.ReadAsStringAsync().Result);

            return(phoneBookEntry);
        }
예제 #16
0
        public void Adds()
        {
            // Arrange
            var sut = new PhoneBook(new PhoneBookEntry[0]);
            // Act
            var data = new PhoneBookEntry("JkHASD", 45654654);

            sut.Add(data);
            // Assert
            Assert.IsTrue(sut.Addresses.Count() == 1 && sut.Addresses[data.Name] == data.Number);
        }
예제 #17
0
 public ActionResult Edit([Bind(Include = "phonebookentryid,phonebookid,name,phonenumber,datecreated,datemodified,active")] PhoneBookEntry phoneBookEntry)
 {
     if (ModelState.IsValid)
     {
         db.Entry(phoneBookEntry).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.phonebookid = new SelectList(db.PhoneBooks, "phonebookid", "name", phoneBookEntry.phonebookid);
     return(View(phoneBookEntry));
 }
예제 #18
0
        public IHttpActionResult GetPhoneBookEntry(int id)
        {
            PhoneBookEntry phoneBookEntry = db.PhoneBookEntries.Find(id);

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

            return(Ok(phoneBookEntry));
        }
예제 #19
0
        public async Task Setup()
        {
            _database = Substitute.For <IDatabase>();

            repo = new PhoneBookRepository(_database);

            var payload = new PhoneBookEntry {
                Name        = "Jon Doe",
                PhoneNumber = "+2710 555 12 12"
            };
        }
예제 #20
0
        public async Task <IActionResult> Put(PhoneBookEntry phoneBookEntryModel)
        {//should use view-edit-models
            try
            {
                await phoneBookEntryService.EditPhoneBookEntryAsync(phoneBookEntryModel);

                return(new OkResult());
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex.Message));
            }
        }
예제 #21
0
        public async Task <ActionResult <PhoneBookEntry> > PutAsync(int id, [FromBody] PhoneBookEntry PhonebookEntry)
        {
            (PhoneBookEntry phonebookEntry, List <ValidationError> errors) = await PhonebookS.EditPhonebookEntryAsync(PhonebookEntry);

            if (errors == null || errors.Count == 0)
            {
                return(phonebookEntry);
            }
            else
            {
                return(BadRequest(errors));
            }
        }
예제 #22
0
        public async Task <ActionResult <PhoneBookEntry> > PostAsync([FromBody] PhoneBookEntry PhonebookEntry)
        {
            (PhoneBookEntry phonebookEntry, List <ValidationError> errors) = await PhonebookS.CreatePhonebookEntryAsync(PhonebookEntry.PhoneBookId, PhonebookEntry.Name, PhonebookEntry.PhoneNumber);

            if (errors == null || errors.Count == 0)
            {
                return(phonebookEntry);
            }
            else
            {
                return(BadRequest(errors));
            }
        }
예제 #23
0
        public ActionResult Add(PhonebookEditViewModel phonebookEditViewModel)
        {
            var contact = new PhoneBook()
            {
                Name        = phonebookEditViewModel.FirstName,
                Surname     = phonebookEditViewModel.LastName,
                CreatedDate = DateTime.Now
            };

            _PhoneBookService.Create(contact);

            var Id = contact.Id;

            if (Id == 0)
            {
                log.Error("Contact not saved. Please try again later!");
                Danger("Contact not saved. Please try again later!");
                return(View("PhoneBookView", phonebookEditViewModel));
            }

            if (phonebookEditViewModel.Numbers.Count() > 0)
            {
                foreach (var entry in phonebookEditViewModel.Numbers)
                {
                    var phonebookEntry = new PhoneBookEntry()
                    {
                        PhoneBookId     = Id,
                        PhoneBookTypeId = Convert.ToInt32(entry.PhoneBookTypeId),
                        Number          = entry.Number
                    };

                    _PhoneBookEntryService.Create(phonebookEntry);
                    Id = phonebookEntry.Id;

                    if (Id == 0)
                    {
                        log.Error($"Contact number {entry.Number} not saved {phonebookEditViewModel.FirstName}!");

                        Danger($"Contact number {entry.Number} not saved {phonebookEditViewModel.FirstName}!");

                        return(View("PhoneBookView", phonebookEditViewModel));
                    }
                }
            }

            Success(string.Format("<b>{0}</b> was successfully saved to the Phonebook.", phonebookEditViewModel.FirstName), true);

            PhonebookHub.BroadcastData();

            return(RedirectToAction("Index", "Phonebook"));
        }
예제 #24
0
        public IHttpActionResult DeletePhoneBookEntry(int id)
        {
            PhoneBookEntry phoneBookEntry = db.PhoneBookEntries.Find(id);

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

            db.PhoneBookEntries.Remove(phoneBookEntry);
            db.SaveChanges();

            return(Ok(phoneBookEntry));
        }
예제 #25
0
        public async Task <IActionResult> Post(int phoneBookId, PhoneBookEntry phoneBookEntryModel)
        {//should use post-model
            try
            {
                await phoneBookEntryService.AddPhoneBookEntryAsync(phoneBookEntryModel.Name, phoneBookEntryModel.PhoneNumber, phoneBookId);

                //Should return created response with the url of the created object
                return(new OkResult());
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(ex.Message));
            }
        }
예제 #26
0
        // GET: PhoneBookEntries/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            PhoneBookEntry phoneBookEntry = db.PhoneBookEntries.Find(id);

            if (phoneBookEntry == null)
            {
                return(HttpNotFound());
            }
            return(View(phoneBookEntry));
        }
예제 #27
0
        public void UpdatesError()
        {
            // Arrange
            var sut = new PhoneBook(new PhoneBookEntry[0]);
            // Act
            var data = new PhoneBookEntry("JkHASD", 45654654);

            sut.Add(data);
            var updated = new PhoneBookEntry("asdasd", 5444);

            sut.Update(updated);
            // Assert
            Assert.IsFalse(sut.Update(updated));
        }
예제 #28
0
        public void Updates()
        {
            // Arrange
            var sut = new PhoneBook(new PhoneBookEntry[0]);
            // Act
            var data = new PhoneBookEntry("JkHASD", 45654654);

            sut.Add(data);
            var updated = new PhoneBookEntry("JkHASD", 5444);

            sut.Update(updated);
            // Assert
            Assert.IsTrue(sut.Addresses.Single().Value == 5444);
        }
예제 #29
0
        // GET: PhoneBookEntries/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            PhoneBookEntry phoneBookEntry = db.PhoneBookEntries.Find(id);

            if (phoneBookEntry == null)
            {
                return(HttpNotFound());
            }
            ViewBag.phonebookid = new SelectList(db.PhoneBooks, "phonebookid", "name", phoneBookEntry.phonebookid);
            return(View(phoneBookEntry));
        }
예제 #30
0
        public async Task AddEntry(PhoneBookEntry entry)
        {
            var existingEntry = await phoneBookRepository.GetById(entry.Name.Trim());

            if (existingEntry != null)
            {
                throw new ApplicationException("An entry with the same name already exists in this phone book. Please use another name or update the existing entry.");
            }

            var phoneBook = new PhoneBook();

            phoneBook.AddEntry(entry);

            await phoneBookRepository.AddEntry(entry);
        }