// Get All basic tables // DEFAULT CRUD public IEnumerable <ContactMapper> GetContacts() { var content = db.Contacts.ToList(); if (content.Count() == 0) { return(null); } else { List <ContactMapper> contacts = new List <ContactMapper>(); foreach (var item in content) { ContactMapper contact = new ContactMapper { ContactId = item.contactId, Email = item.email, FirstName = item.firstName, LastName = item.lastName, ObjectId = item.objectId, PhoneNumber = item.phoneNumber }; contacts.Add(contact); } return(contacts); } }
// PUT api/contacts/5 public HttpResponseMessage Put(int id, [FromBody] Contact contact) { try { var conn = WebApiConfig.GetMySqlConnection(); var command = conn.CreateCommand(); command.CommandText = @"UPDATE contacts SET first=@first, last=@last, dob=@dob, phone=@phone, gender=@gender, rel=@rel, des=@des WHERE id=@id" ; command.Parameters.AddWithValue("@id", id); ContactMapper.GetParametersFromContact(command, contact); conn.Open(); try { if (command.ExecuteNonQuery() != 1) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } } catch { throw; } } catch { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
public ContactModel Update(ContactModel contactModel) { var contact = _contactRepository.GetById(contactModel.Id); if (contact == null) { throw new NotFoundException(Messages.ContactNotFound); } var contactWithName = _contactRepository.GetByName(contactModel.Name); if (contactWithName != null && contact.Id != contactWithName.Id) { throw new ValidationException(Messages.AContactWithThatNameAlreadyExists); } var contactWithPrefixAndNumber = _contactRepository.GetByPrefixAndNumber(contactModel.NumberPrefix.Id, contactModel.Number); if (contactWithPrefixAndNumber != null && contact.Id != contactWithPrefixAndNumber.Id) { throw new ValidationException(Messages.AContactWithThatNumberAlreadyExists); } _contactRepository.Update(ContactMapper.ToEntity(contactModel)); return(contactModel); }
public ContactsController( ContactMapper contactMapper, IContactsService contactsService) { _contactMapper = contactMapper; _contactsService = contactsService; }
// POST api/contacts public HttpResponseMessage Post([FromBody] Contact contact) { try { var conn = WebApiConfig.GetMySqlConnection(); var command = conn.CreateCommand(); command.CommandText = @"INSERT INTO contacts (`id`, `isFavorite`, `first`, `last`, `dob`, `phone`, `gender`, `rel`, `des`) VALUES (NULL, 0, @first, @last, @dob, @phone, @gender, @rel, @des)"; ContactMapper.GetParametersFromContact(command, contact); conn.Open(); try { if (command.ExecuteNonQuery() != 1) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } } catch { throw; } } catch { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
/// <summary> /// Updates a contact. /// </summary> /// <param name="contactId">Contact identifier.</param> /// <param name="contactResource">New contact information</param> /// <returns>Contact information.</returns> public async Task <DataResponse <ContactResource> > UpdateAsync(int contactId, SaveContactResource contactResource) { try { if (contactResource == null) { throw new ArgumentNullException(nameof(contactResource)); } var contact = await _contactRepository.FindByIdAsync(contactId); if (contact == null) { throw new NotFoundException(nameof(Contact), contactId); } ContactMapper.Map(contact, contactResource); _contactRepository.Update(contact); await _unitOfWork.SaveChangesAsync(); var resource = _mapper.Map <Contact, ContactResource>(contact); return(new DataResponse <ContactResource>(resource)); } catch (Exception ex) { Console.WriteLine(ex.Message); return(new DataResponse <ContactResource>(ex.Message)); } }
public void MapToContactList_WhenMapping_ThenFieldsAreMappedAsExpected() { var mappedContactResult = ContactMapper.MapToContactList(contactsList); Assert.IsNotNull(mappedContactResult, "Contact Result is not null"); Assert.AreEqual(contactsList[0].Id, mappedContactResult[0].Id, "Id"); Assert.AreEqual(contactsList[0].FirstName, mappedContactResult[0].FirstName, "FirstName"); Assert.AreEqual(contactsList[0].LastName, mappedContactResult[0].LastName, "LastName"); Assert.AreEqual(contactsList[0].Email, mappedContactResult[0].Email, "Email"); Assert.AreEqual(contactsList[0].Phone, mappedContactResult[0].Phone, "Phone"); Assert.AreEqual(contactsList[0].Status, mappedContactResult[0].Status, "Status"); Assert.AreEqual(contactsList[1].Id, mappedContactResult[1].Id, "Id"); Assert.AreEqual(contactsList[1].FirstName, mappedContactResult[1].FirstName, "FirstName"); Assert.AreEqual(contactsList[1].LastName, mappedContactResult[1].LastName, "LastName"); Assert.AreEqual(contactsList[1].Email, mappedContactResult[1].Email, "Email"); Assert.AreEqual(contactsList[1].Phone, mappedContactResult[1].Phone, "Phone"); Assert.AreEqual(contactsList[1].Status, mappedContactResult[1].Status, "Status"); Assert.AreEqual(contactsList[2].Id, mappedContactResult[2].Id, "Id"); Assert.AreEqual(contactsList[2].FirstName, mappedContactResult[2].FirstName, "FirstName"); Assert.AreEqual(contactsList[2].LastName, mappedContactResult[2].LastName, "LastName"); Assert.AreEqual(contactsList[2].Email, mappedContactResult[2].Email, "Email"); Assert.AreEqual(contactsList[2].Phone, mappedContactResult[2].Phone, "Phone"); Assert.AreEqual(contactsList[2].Status, mappedContactResult[2].Status, "Status"); }
// GET api/contacts public HttpResponseMessage Get() { List <Contact> list = new List <Contact>(); try { var conn = WebApiConfig.GetMySqlConnection(); var command = conn.CreateCommand(); command.CommandText = "SELECT * FROM contacts"; conn.Open(); try { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var contact = ContactMapper.GetContactFromReader(reader); list.Add(contact); } } } catch { throw; } } catch { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } return(Request.CreateResponse(HttpStatusCode.OK, list)); }
public static async Task Run( [QueueTrigger("contacts", Connection = "AzureWebJobsStorage")] string contactJson, ILogger log, ExecutionContext context) { var logPrefix = GetLogPrefix(); log.LogInformation($"{logPrefix}: {contactJson}"); var contactFromFile = JsonConvert.DeserializeObject <FileUploadContact>(contactJson); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", true, true) .AddEnvironmentVariables() .Build(); var sqlConnectionString = config.GetConnectionString("Sql"); var fileUploadContext = new FileUploadContext(sqlConnectionString); var getEmployerQuery = new GetEmployerQuery(fileUploadContext); var employerInSql = await getEmployerQuery.Execute(contactFromFile.CompanyName, contactFromFile.CreatedOnCompany); if (employerInSql == null) { // TODO Employer has to exist } var getContactQuery = new GetContactQuery(fileUploadContext); var contactInSql = await getContactQuery.Execute(contactFromFile.CompanyName, contactFromFile.CreatedOnCompany); var contact = ContactMapper.Map(contactFromFile, contactInSql, employerInSql.Id); if (contactInSql == null) { log.LogInformation($"{logPrefix} Creating Contact: {contactFromFile.Contact}"); var createEmployerCommand = new CreateContactCommand(fileUploadContext); await createEmployerCommand.Execute(contact); log.LogInformation($"{logPrefix} Created Contact: {contactFromFile.Contact}"); } else { var areEqual = contactInSql.Equals(contact); if (!areEqual) { log.LogInformation($"{logPrefix} Updating Contact: {contactFromFile.Contact}"); var updateContactCommand = new UpdateContactCommand(fileUploadContext); await updateContactCommand.Execute(contact); log.LogInformation($"{logPrefix} Updated Contact: {contactFromFile.Contact}"); } } log.LogInformation($"{logPrefix} Processed Contact: {contactFromFile.Contact}"); }
public CfContactQueryResult QueryContacts(CfQueryContacts queryContacts) { var resourceList = BaseRequest <ResourceList>(HttpMethod.Get, new QueryContacts(queryContacts), new CallfireRestRoute <Contact>()); var contact = resourceList.Resource == null ? null : resourceList.Resource.Select(r => ContactMapper.FromContact((Contact)r)).ToArray(); return(new CfContactQueryResult(resourceList.TotalResults, contact)); }
public async Task <List <DAL.App.DTO.Contact> > AllForUserAsync(int userId) { return(await RepositoryDbSet .Include(c => c.ContactType) .ThenInclude(m => m.ContactTypeValue) .ThenInclude(t => t.Translations) .Include(c => c.Person) .Where(c => c.Person.AppUserId == userId) .Select(e => ContactMapper.MapFromDomain(e)).ToListAsync()); }
public async Task UpdateContact(ContactDto contactDto) { var contact = ContactMapper.FromDto(contactDto); // check organisation exists contact.Organisation = await _unitOfWork.OrganisationRepository.GetByIdAsync(contactDto.OrganisationId) ?? throw new EntityNotFoundException($"organisation with id <{contactDto.OrganisationId}> not found");; _unitOfWork.ContactRepository.Update(contact); await _unitOfWork.SaveAsync(); }
public async Task <DAL.App.DTO.Contact> FindForUserAsync(int id, int userId) { var contact = await RepositoryDbSet .Include(c => c.ContactType) .ThenInclude(m => m.ContactTypeValue) .ThenInclude(t => t.Translations) .Include(c => c.Person) .FirstOrDefaultAsync(m => m.Id == id && m.Person.AppUserId == userId); return(ContactMapper.MapFromDomain(contact)); }
public async Task <int> AddContact(ContactDto contact) { try { return(await _contactRepository.AddContact(ContactMapper.MapFromDto(contact))); } catch (ArgumentException) { throw; } }
public override void Configure(Container container) { //containers HttpServiceContainer.Build(container); SearchContainer.Build(container); // mappings AllergyMapper.Build(); GoalsMapper.Build(); AllergyMedSearchMapper.Build(); MedSuppMapper.Build(); PatientNoteMapper.Build(); PatientSystemMapper.Build(); PatientContactMapper.Build(); ContactTypeLookUpsMappers.Build(); ContactMapper.Build(); Plugins.Add(new RequestLogsFeature() { RequiredRoles = new string[] {} }); // request filtering for setting global vals. RequestFilters.Add((req, res, requestDto) => { HostContext.Instance.Items.Add("Contract", ((IAppDomainRequest)requestDto).ContractNumber); HostContext.Instance.Items.Add("Version", ((IAppDomainRequest)requestDto).Version); }); RequestFilters.Add((req, res, requestDto) => { var obj = req.ResponseContentType; }); var emitGlobalHeadersHandler = new CustomActionHandler((httpReq, httpRes) => httpRes.EndRequest()); SetConfig(new EndpointHostConfig { RawHttpHandlers = { (httpReq) => httpReq.HttpMethod == HttpMethods.Options ? emitGlobalHeadersHandler : null }, GlobalResponseHeaders = { //{"Access-Control-Allow-Origin", "*"}, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, { "Access-Control-Allow-Headers", "Content-Type" }, }, AllowJsonpRequests = true }); // initialize datetime format JsConfig.DateHandler = JsonDateHandler.ISO8601; }
/// <summary> /// Updates a reservation. /// </summary> /// <param name="reservationId">Reservation identifier.</param> /// <param name="reservationResource">New reservation information</param> /// <returns>Reservation information.</returns> public async Task <DataResponse <ReservationResource> > UpdateAsync(int reservationId, SaveReservationResource reservationResource) { try { if (reservationResource == null) { throw new ArgumentNullException(nameof(reservationResource)); } var reservation = await _reservationRepository.FindByIdAsync(reservationId); if (reservation == null) { throw new NotFoundException(nameof(Reservation), reservationId); } var place = await _placeRepository.FindByIdAsync(reservationResource.PlaceId); reservation.Place = place ?? throw new NotFoundException(nameof(Place), reservationResource.PlaceId); if (reservationResource.Contact != null) { var contact = await _contactRepository.FirstOrDefaultAsync( new ContactsByNameSpec(reservationResource.Contact.Name)); if (contact != null) { ContactMapper.Map(contact, reservationResource.Contact); reservation.Contact = contact; } else { reservation.Contact = _mapper.Map <Contact>(reservationResource.Contact); } } ReservationMapper.Map(reservation, reservationResource); _reservationRepository.Update(reservation); await _unitOfWork.SaveChangesAsync(); var resource = _mapper.Map <ReservationResource>(reservation); return(new DataResponse <ReservationResource>(resource)); } catch (Exception ex) { Console.WriteLine(ex.Message); return(new DataResponse <ReservationResource>(ex.Message)); } }
public async Task UpdateContact(ContactDto contact) { try { await _contactRepository.UpdateContact(ContactMapper.MapFromDto(contact)); } catch (ArgumentException) { throw; } catch (InvalidOperationException) { throw; } }
public IActionResult CreateEmail(ContactViewModel contact) { try { _contact.SendEmail(ContactMapper.Map(contact)); return(RedirectToAction("Index")); } catch (Exception) { ErrorViewModel model = new ErrorViewModel { RequestId = "Kunne ikke Sende Email" }; return(View("Error", model)); } }
/// <summary> /// Get Contact List /// </summary> /// <returns>Returns list of Contact</returns> public async Task <List <ContactResponse> > GetContactList() { ContactDAL contactDAL = new ContactDAL(eHIDemoContext); Task <List <DBModel.Contact.Contact> > getContactList = Task.Run(() => contactDAL.GetContactList()); List <DBModel.Contact.Contact> contactList = await getContactList.ConfigureAwait(false); List <ContactResponse> contactResponse = new List <ContactResponse>(); if (contactList.Count > 0) { contactResponse = ContactMapper.MapperForContactList(contactList); } return(contactResponse); }
/// <summary> /// Update Contact /// </summary> /// <param name="contactRequest">contactRequest</param> /// <returns>Returns true if updation is successful else false</returns> public async Task <bool> UpdateContact(ContactRequest contactRequest) { ContactValidator contactValidator = new ContactValidator(eHIDemoContext); contactValidator.ValidateContactRequest(contactRequest); ContactDAL contactDAL = new ContactDAL(eHIDemoContext); DBModel.Contact.Contact contact = ContactMapper.MapperForContactUpdate(contactRequest); int savedRecordCount = await contactDAL.UpdateContact(contact).ConfigureAwait(false); if (savedRecordCount > 0) { return(true); } return(false); }
public IActionResult Get(string id) { if (!ObjectId.TryParse(id, out var objectId)) { return(BadRequest("'Id' parameter is ivalid ObjectId")); } var contact = _contactManager.GetContactById(objectId); if (contact == null) { return(NotFound()); } return(Ok(ContactMapper.ContactToContactModel(contact))); }
public async Task <int> CreateContact(ContactDto contactDto) { var contact = ContactMapper.FromDto(contactDto); contact.Organisation = await _unitOfWork.OrganisationRepository.GetByIdAsync(contact.OrganisationId); if (contact.Organisation == null) { throw new EntityNotFoundException($"organisation with id <{contact.OrganisationId}> not found"); } await _unitOfWork.ContactRepository.InsertAsync(contact); await _unitOfWork.SaveAsync(); return(contact.Id); }
public CfContactSource(object[] items) { if (items != null && items.Any()) { if (items.GetValue(0).GetType() == typeof(Contact)) { Items = items.Select(i => ContactMapper.FromContact(i as Contact)).ToArray(); } else if (items.GetValue(0).GetType() == typeof(ContactSourceNumbers)) { Items = items.Select(i => ContactSourceNumbersMapper.FromContactSourceNumbers(i as ContactSourceNumbers)).ToArray(); } else { Items = items; } } }
public IActionResult Post([FromBody] ContactSavingModel contactToCreateModel, string team) { if (team != null) { var teamName = nameof(contactToCreateModel.Team); contactToCreateModel.Team = team; ModelState.ClearError(teamName); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var contactToCreate = ContactMapper.ContactModelToContact(contactToCreateModel); return(Ok(_contactManager.CreateContact(contactToCreate).ToString())); }
public ContactContract Process(GetContactRequest input) { var parameter = new GetContact { OrganizationId = input.OrganizationId, Id = input.Id }; _query.BuildQuery(parameter); using (DapperUnitOfWork.Begin()) { var contact = _runner.Run(_query); var result = ContactMapper.Map(contact); return(result); } }
static void Main(string[] args) { freshdesk = new FreshdeskRepository(); accountMapper = new AccountMapper(); contactMapper = new ContactMapper(); ticketMapper = new TicketMapper(); crm = new CrmRepository(); string dayOfWeek = DateTime.Now.DayOfWeek.ToString(); if (dayOfWeek == "Saturday") { AgentSync(); } AccountSync(); ContactSync(); TicketSync(); }
public ICollection <TRelatedModel> GetRelated <TRelatedModel>(int objectID) where TRelatedModel : BusinessBase { IMapper mapper = null; if (typeof(TRelatedModel) == typeof(Brand)) { mapper = new BrandMapper(); } else if (typeof(TRelatedModel) == typeof(Cancellation)) { mapper = new CancellationMapper(); } if (typeof(TRelatedModel) == typeof(Contact)) { mapper = new ContactMapper(); } else if (typeof(TRelatedModel) == typeof(LegalCase)) { mapper = new LegalCaseMapper(); } else if (typeof(TRelatedModel) == typeof(Opposition)) { mapper = new OppositionMapper(); } else if (typeof(TRelatedModel) == typeof(TMRepresentative)) { mapper = new TMRepresentativeMapper(); } else if (typeof(TRelatedModel) == typeof(Trademark)) { mapper = new TrademarkMapper(); } else if (typeof(TRelatedModel) == typeof(TrademarkOwner)) { mapper = new TrademarkOwnerMapper(); } using (var repository = new Repository <TModel>(this._connectionString, mapper)) { return(repository.GetRelated <TRelatedModel>(objectID, mapper)); } }
// Get Single basic table // DEFAULT CRUD public ContactMapper GetContact(int contactId) { var content = db.Contacts.FirstOrDefault(i => i.contactId == contactId); if (content == null) { return(null); } else { ContactMapper contact = new ContactMapper { ContactId = content.contactId, Email = content.email, FirstName = content.firstName, LastName = content.lastName, ObjectId = content.objectId, PhoneNumber = content.phoneNumber }; return(contact); } }
public List <ContactDTO> GetAllContacts(DateTime modifiedOnOrAfter) { _getMessage?.Invoke("Loading contacts started"); ContactsController contactController = new ContactsController(_apiKey, _baseURL); ListRequestOptions opts = new ListRequestOptions { PropertiesToInclude = new List <string> { "firstname", "lastname", "lifecyclestage", "associatedcompanyid" } }; opts.Limit = 100; opts.timeOffset = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds(); List <ContactDTO> contactList = new List <ContactDTO>(); bool hasMore = true; while (hasMore) { ContactListResponse pageContacts = contactController.GetPageContacts(opts); ContactMapper.ToContactList(pageContacts, ref contactList, modifiedOnOrAfter, out hasMore); _getMessage?.Invoke($"Loaded {contactList.Count} contacts"); hasMore = hasMore & pageContacts.HasMore; if (hasMore) { opts.timeOffset = pageContacts.TimeOffset; } } List <CompanyResponse> companyResponseList = GetAllCompanies(contactList); ContactMapper.Map(ref contactList, companyResponseList); return(contactList); }
public async Task <ContactModel> AddAsync(ContactModel contactModel) { var contactWithName = await _contactRepository.GetByNameAsync(contactModel.Name); if (contactWithName != null) { throw new ValidationException(Messages.AContactWithThatNameAlreadyExists); } var contactWithPrefixAndNumber = await _contactRepository.GetByPrefixAndNumberAsync(contactModel.NumberPrefix.Id, contactModel.Number); if (contactWithPrefixAndNumber != null) { throw new ValidationException(Messages.AContactWithThatNumberAlreadyExists); } var id = await _contactRepository.AddAsync(ContactMapper.ToEntity(contactModel)); contactModel.Id = id; return(contactModel); }