public async Task <CustomerDetailItem> CreateCustomerAsync([FromBody] CustomerPayloadItem payload) { var dbItem = new Customer { Id = Guid.NewGuid(), City = payload.City, CountryId = payload.Country.Id, FirstName = payload.FirstName, LastName = payload.LastName, Phone = payload.Phone, Street = payload.Street, ZipCode = payload.ZipCode, Created = DateTime.UtcNow, }; _db.Add(dbItem); var entry = _db.Entry(dbItem); entry.UpdateAdditionalProperties(payload); await _db.SaveChangesAsync(); return(await GetCustomerDetailItemAsync(dbItem.Id)); }
public async Task <ActionResult <Recruiter> > Post([FromBody] BindRecruiter bindRecruiter) { try { if (bindRecruiter != null) { var newRecruiter = new Recruiter() { Name = bindRecruiter.Name, Email = bindRecruiter.Email, Phone = bindRecruiter.Phone }; _context.Recruiters.Add(newRecruiter); await _context.SaveChangesAsync(); var insertedRecruiter = _context.Recruiters.Where(j => j.RecruiterId == newRecruiter.RecruiterId); if (insertedRecruiter != null) { return(CreatedAtAction(nameof(newRecruiter), new { id = newRecruiter.RecruiterId }, newRecruiter)); } } return(BadRequest()); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <Offer> CreateAsync(Offer offer) { var offerRecord = _mapper.Map <DataProvider.Models.Offer>(offer); // offernumber is set on creation and doesn't change afterwards. No matter what happens to the offer date var date = offer.OfferDate == null ? DateTimeOffset.UtcNow.UtcDateTime : (DateTime)offer.OfferDate; var offerNumberDate = $"{(date.Year + 10).ToString().Substring(2, 2)}/{date.ToString("MM")}/{date.ToString("dd")}/"; var sequenceNumber = await _sequenceDataProvider.GetNextOfferSequenceNumberAsync(offerNumberDate); offerRecord.SequenceNumber = sequenceNumber; var offerNumber = $"{offerNumberDate}{sequenceNumber.ToString("D2")}"; offerRecord.Number = offerNumber; await EmbedCityAsync(offerRecord); offerRecord.Currency = "EUR"; _context.Offers.Add(offerRecord); await _context.SaveChangesAsync(); // EF Core requires to create an order record as well because offer and order share the same underlying SQL table var orderRecord = _mapper.Map <DataProvider.Models.Order>(offerRecord); _context.Orders.Add(orderRecord); await _context.SaveChangesAsync(); return(_mapper.Map <Offer>(offerRecord)); }
public async Task <IActionResult> PutCandidateStatus([FromRoute] int id, [FromBody] CandidateStatus candidateStatus) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != candidateStatus.CandidateStatusId) { return(BadRequest()); } _context.Entry(candidateStatus).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CandidateStatusExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <Order> CreateAsync(Order order) { // Order has already been created by EF Core on creation of the offer since they share the same underlying SQL table var existingOrderRecord = await _context.Orders.Where(o => o.Id == order.Offer.Id).IgnoreQueryFilters().FirstOrDefaultAsync(); if (existingOrderRecord == null) { var message = $"Expected order {order.Id} to exist already in EF Core, but none was found."; _logger.LogError(message); throw new CodedException("InvalidState", "Unable to create order", message); } order.Id = existingOrderRecord.Id; // Set existing id on the new incoming order. Id of the incoming order is null. // Make it a valid order existingOrderRecord.IsOrdered = true; existingOrderRecord.Currency = "EUR"; _mapper.Map(order, existingOrderRecord); _context.Orders.Update(existingOrderRecord); await _context.SaveChangesAsync(); return(_mapper.Map <Order>(existingOrderRecord)); }
public async Task <IActionResult> CreateUserAsync([FromBody] RegisterUser registerUserModel) { try { if (!ModelState.IsValid) { return(BadRequest()); } if (registerUserModel.Password != registerUserModel.ConfirmPassword) { return(BadRequest()); } if (String.IsNullOrEmpty(registerUserModel.Name) || String.IsNullOrEmpty(registerUserModel.Email)) { return(BadRequest()); } var recruiter = new Recruiter() { Email = registerUserModel.Email, Name = registerUserModel.Name, Phone = registerUserModel.Phone, }; _context.Recruiters.Add(recruiter); await _context.SaveChangesAsync(); var newUser = new ApplicationUser() { UserName = registerUserModel.UserName, Recruiter = recruiter }; var result = await _userManager.CreateAsync(newUser, registerUserModel.Password); if (result.Succeeded) { result = _userManager.AddClaimsAsync(newUser, new Claim[] { new Claim(DefinedClaimTypes.RecruiterId, newUser.Recruiter.RecruiterId.ToString()), new Claim(JwtClaimTypes.Name, newUser.Recruiter.Name), new Claim(DefinedClaimTypes.Access, registerUserModel.AccessClaim), }).Result; if (!String.IsNullOrEmpty(registerUserModel.Email)) { await _userManager.SetEmailAsync(newUser, registerUserModel.Email); } return(Ok()); } return(BadRequest()); } catch (Exception ex) { var debugEx = ex; return(BadRequest()); } }
public async Task <T> CreateAsync(T entity) { NullCheck(entity); await _entitySet.AddAsync(entity); await _context.SaveChangesAsync(); return(entity); }
public async Task <Intervention> CreateAsync(Intervention intervention) { var interventionRecord = _mapper.Map <DataProvider.Models.Intervention>(intervention); _context.Interventions.Add(interventionRecord); await _context.SaveChangesAsync(); return(_mapper.Map <Intervention>(interventionRecord)); }
public async Task <Offerline> CreateAsync(Offerline offerline) { var offerlineRecord = _mapper.Map <DataProvider.Models.Offerline>(offerline); offerlineRecord.Currency = "EUR"; _context.Offerlines.Add(offerlineRecord); await _context.SaveChangesAsync(); return(_mapper.Map <Offerline>(offerlineRecord)); }
public async Task <IActionResult> PutJob([FromRoute] int id, [FromBody] BindJob bindJob) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != bindJob.JobId) { return(BadRequest()); } var updatedJob = await _context.Jobs .FirstOrDefaultAsync(j => j.JobId == bindJob.JobId); if (!User.HasClaim(claim => (claim.Type == DefinedClaimTypes.RecruiterId && claim.Value == updatedJob.RecruiterId.ToString()) || (claim.Type == DefinedClaimTypes.Access && claim.Value == DefinedClaimAccessValues.Elevated))) { return(BadRequest()); } updatedJob.Title = bindJob.Title; updatedJob.Remarks = bindJob.Remarks; updatedJob.BaseSalary = bindJob.BaseSalary; updatedJob.Fee = bindJob.Fee; updatedJob.StartDate = bindJob.StartDate; if (bindJob.ClientId > 0 & updatedJob.ClientId != bindJob.ClientId) { updatedJob.Client = await _context.CrmClients.FirstOrDefaultAsync(cl => cl.ClientId == bindJob.ClientId); } if (bindJob.JobStatusId > 0) { updatedJob.JobStatus = await _context.JobStatuses.FirstOrDefaultAsync(js => js.JobStatusId == bindJob.JobStatusId); } _context.Entry(updatedJob).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!JobExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> Create([Bind("FullName,Phone,Email,Company,Status,Id,DateCreated,CreatedBy")] Customer customer) { if (ModelState.IsValid) { _context.Add(customer); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(customer)); }
public async Task <WorkingHour> CreateAsync(WorkingHour workingHour) { var workingHourRecord = _mapper.Map <DataProvider.Models.WorkingHour>(workingHour); workingHourRecord.Hours = 1; _context.WorkingHours.Add(workingHourRecord); await _context.SaveChangesAsync(); return(_mapper.Map <WorkingHour>(workingHourRecord)); }
public async Task <ActionResult <Contact> > CreateContact([FromBody] Contact c) { if (c == null) { return(NotFound()); } _context.Contact.Add(c); await _context.SaveChangesAsync(); return(CreatedAtAction("GetContact", new { id = c.Id }, c)); }
public async Task <Request> CreateAsync(Request request) { var requestRecord = _mapper.Map <DataProvider.Models.Request>(request); await EmbedCityAsync(requestRecord); _context.Requests.Add(requestRecord); await _context.SaveChangesAsync(); return(_mapper.Map <Request>(requestRecord)); }
public async Task <ActionResult <Campaign> > CreateCampaign([FromBody] Campaign c) { if (c == null) { return(NotFound()); } _context.Campaign.Add(c); await _context.SaveChangesAsync(); return(CreatedAtAction("GetCampaign", new { id = c.Id }, c)); }
public async Task <InvoiceSupplement> CreateAsync(InvoiceSupplement invoiceSupplement) { var invoiceSupplementRecord = _mapper.Map <DataProvider.Models.InvoiceSupplement>(invoiceSupplement); invoiceSupplementRecord.Currency = "EUR"; invoiceSupplementRecord.SequenceNumber = 0; _context.InvoiceSupplements.Add(invoiceSupplementRecord); await _context.SaveChangesAsync(); return(_mapper.Map <InvoiceSupplement>(invoiceSupplementRecord)); }
// Creation of a Visit is handled by the RequestDataProvider // Visit can only be created on creation of a new request public async Task <CalendarEvent> UpdateAsync(CalendarEvent calendarEvent) { DataProvider.Models.Visit visitRecord = null; // calendar event doesn't necessarily have an id, since it may not be created yet (while the underlying visit record already exists) if (calendarEvent.Id != 0) { visitRecord = await FindByIdAsync(calendarEvent.Id); } else { visitRecord = await FindWhereAsync(v => v.RequestId == calendarEvent.Request.Id); } _mapper.Map(calendarEvent, visitRecord); _context.Visits.Update(visitRecord); await _context.SaveChangesAsync(); var savedCalendarEvent = _mapper.Map <CalendarEvent>(visitRecord); if (savedCalendarEvent != null) // maybe null if the domain resource 'CalendarEvent' has been removed { savedCalendarEvent.Period = calendarEvent.Period; savedCalendarEvent.FromHour = calendarEvent.FromHour; savedCalendarEvent.UntilHour = calendarEvent.UntilHour; } return(savedCalendarEvent); }
public async Task <AccountancyExport> CreateAsync(AccountancyExport accountancyExport) { var accountancyExportRecord = _mapper.Map <DataProvider.Models.AccountancyExport>(accountancyExport); _context.AccountancyExports.Add(accountancyExportRecord); using (var transaction = _context.Database.BeginTransaction()) { try { await GenerateExportFilesAsync((int)accountancyExport.FromNumber, (int)accountancyExport.UntilNumber, accountancyExport.IsDryRun); await _context.SaveChangesAsync(); transaction.Commit(); return(_mapper.Map <AccountancyExport>(accountancyExportRecord)); } catch (InvalidDataException e) { transaction.Rollback(); throw e; } } }
public async Task SaveLog(CustomLogger logger) { #if !DEBUG await _dbContext.Set <CustomLogger>().AddAsync(logger); await _dbContext.SaveChangesAsync(); #endif }
protected override async Task Handle(AddCustomer request, CancellationToken cancellationToken) { // map from the Command data to the EF entity. var entity = mapper.Map <DataModel.Customer>(request); context.Customers.Add(entity); await context.SaveChangesAsync(cancellationToken); }
public async Task <ActionResult <Client> > Post([FromBody] BindClient bindClient) { try { if (bindClient != null) { if (bindClient.RecruiterId < 1) { return(BadRequest()); } var newClient = new Client() { ContactPerson = bindClient.ContactPerson, CompanyName = bindClient.CompanyName, Email = bindClient.Email, TelephoneOffice = bindClient.TelephoneOffice, TelephoneMobile = bindClient.TelephoneMobile, Designation = bindClient.Designation, Remarks = bindClient.Remarks, Address = bindClient.Address }; if (bindClient.RecruiterId > 0) { newClient.Recruiter = await _context.Recruiters.FirstOrDefaultAsync(r => r.RecruiterId == bindClient.RecruiterId); } _context.CrmClients.Add(newClient); await _context.SaveChangesAsync(); var insertedClient = _context.CrmClients.Where(j => j.ClientId == newClient.ClientId); if (insertedClient != null) { return(CreatedAtAction(nameof(newClient), new { id = newClient.ClientId }, newClient)); } } return(BadRequest()); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
// public async Task<IActionResult> AddNewCompany(Company companyIn) public async Task <IActionResult> AddNewCompany([BindAttribute("Name, City, CUI, J, Adress, HasAutoPark, FieldOfActivity, NrOfDrivers")] Company companyIn) { if (ModelState.IsValid) { ViewData["Message"] = "You Have added :"; context.Add(companyIn); await context.SaveChangesAsync(); return(View(companyIn)); } ViewData["Message"] = "Please fill all mandatory field:"; return(View(companyIn)); }
public async Task <IActionResult> PostCandidateSentToInterview([FromBody] CandidateSentToIntrerviewBindModel bindCandidate) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var job = await _context.Jobs.Include(j => j.Recruiter).FirstOrDefaultAsync(j => j.JobId == bindCandidate.JobId); if (!User.HasClaim(claim => (claim.Type == DefinedClaimTypes.RecruiterId && claim.Value == job.RecruiterId.ToString()) || (claim.Type == DefinedClaimTypes.Access && claim.Value == DefinedClaimAccessValues.Elevated))) { return(BadRequest()); } var candidateSent = new CandidateSentToIntrerview(); if (bindCandidate.JobId > 0 && bindCandidate.CandidateId > 0) { var checkForExistingRecord = await _context.CandidatesSentToInterview.FirstOrDefaultAsync(cs => cs.CandidateId == bindCandidate.CandidateId && cs.JobId == bindCandidate.JobId); if (checkForExistingRecord == null) { candidateSent.JobId = bindCandidate.JobId; candidateSent.CandidateId = bindCandidate.CandidateId; } } else { return(BadRequest()); } _context.CandidatesSentToInterview.Add(candidateSent); await _context.SaveChangesAsync(); return(Ok()); }
public async Task <Telephone> CreateAsync(Telephone telephone) { var telephoneRecord = _mapper.Map <DataProvider.Models.Telephone>(telephone); _context.Telephones.Add(telephoneRecord); try { await _context.SaveChangesAsync(); return(_mapper.Map <Telephone>(telephoneRecord)); } catch (Microsoft.EntityFrameworkCore.DbUpdateException e) { if (e.InnerException.Message.Contains("insert duplicate key in object")) { throw new EntityAlreadyExistsException(); } else { throw e; } } }
public async Task <CountryInfo> CreateCountryAsync([FromBody] CountryPayload payload) { var dbItem = new Country { Id = Guid.NewGuid(), Name = payload.Name, Iso3 = payload.Iso3, }; _db.Add(dbItem); await _db.SaveChangesAsync(); return(await GetCountryInfoByIdAsync(dbItem.Id)); }
public async Task <Deposit> CreateAsync(Deposit deposit) { var depositRecord = _mapper.Map <DataProvider.Models.Deposit>(deposit); if (depositRecord.OrderId != null) { depositRecord.SequenceNumber = await _sequenceDataProvider.GetNextDepositSequenceNumberAsync((int)depositRecord.OrderId); var invoice = await _context.Orders.Where(o => o.Id == depositRecord.OrderId).Select(o => o.Invoice).FirstOrDefaultAsync(); if (invoice != null) { depositRecord.InvoiceId = invoice.Id; } } depositRecord.Currency = "EUR"; depositRecord.IsDeposit = true; // should be set to false if created while an invoice is already attached? _context.Deposits.Add(depositRecord); await _context.SaveChangesAsync(); return(_mapper.Map <Deposit>(depositRecord)); }
public async Task <IActionResult> AddCustomerResponses(string customerId, string responseId) { var response = await _context.Responses.FindAsync(responseId); await _context.CustomerResponses.AddAsync(new CustomerResponse { CustomerId = customerId, QuestionId = response.QuestionId, ResponseId = responseId, }); await _context.SaveChangesAsync(); string isFirst = "false"; return(RedirectToAction(nameof(AddCustomerExperience), new { customerId, responseId, isFirst })); }
public async Task <IActionResult> Delete(int id) { try { var document = await _context.Documents .FirstOrDefaultAsync(d => d.FileRepresentationInDatabaseId == id); if (document == null) { return(NotFound()); } _savedDocumentHandler.DeleteDocument(document.Name); _context.Remove(document); await _context.SaveChangesAsync(); return(NoContent()); } catch (Exception ex) { var debugEx = ex; return(BadRequest()); } }
public async Task <IActionResult> PutCandidate([FromRoute] int id, [FromBody] BindCandidate bindCandidate) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != bindCandidate.CandidateId) { return(BadRequest()); } if (!User.HasClaim(claim => (claim.Type == DefinedClaimTypes.RecruiterId && claim.Value == bindCandidate.RecruiterId.ToString()) || (claim.Type == DefinedClaimTypes.Access && claim.Value == DefinedClaimAccessValues.Elevated))) { return(BadRequest()); } var updatedCandidate = await _context.Candidates.FirstOrDefaultAsync(c => c.CandidateId == bindCandidate.CandidateId); updatedCandidate.Name = bindCandidate.Name; updatedCandidate.Email = bindCandidate.Email; updatedCandidate.Phone = bindCandidate.Phone; if (bindCandidate.JobId > 0) { var candidateSent = new CandidateSentToIntrerview() { JobId = bindCandidate.JobId, CandidateId = bindCandidate.CandidateId }; _context.CandidatesSentToInterview.Add(candidateSent); } if (bindCandidate.RecruiterId > 0) { updatedCandidate.Recruiter = await _context.Recruiters.FirstOrDefaultAsync(r => r.RecruiterId == bindCandidate.RecruiterId); } if (bindCandidate.CandidateStatusId > 0) { updatedCandidate.CandidateStatus = await _context.CandidateStatuses.FirstOrDefaultAsync(s => s.CandidateStatusId == bindCandidate.CandidateStatusId); } _context.Entry(updatedCandidate).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CandidateExists(id)) { return(NotFound()); } else { return(BadRequest()); } }catch (Exception ex) { var debugEx = ex; return(BadRequest()); } return(NoContent()); }
private async Task ExecuteTrigger(Trigger t) { string expression = t.GetExpression(); object[] p = t.GetParams(); Type objType = Type.GetType("Crm." + t.Table); if (t.Table.ToLower() == "contact") { foreach (var action in t.Actions) { var contacts = _crmContext.Contact.Where(expression, p).ToList(); // Type contactType = contact.GetType(); if (action.Type.ToLower() == "update") { if (contacts != null) { foreach (var contact in contacts) { if (action.MetaData == null) { continue; } string[] values = action.Value.Split("_"); string[] fields = action.MetaData.Field.Split("_"); if (values.Length != fields.Length) { throw new Exception(nameof(action)); } int count = 0; foreach (var field in fields) { foreach (var prop in contact.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (prop.Name.ToLower() == field.ToLower()) { // FieldInfo fieldInfo = contactType.GetFieldInfo(prop.Name); // fieldInfo.SetValue(null, action.Value); var propType = prop.PropertyType; var targetType = propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)) ? Nullable.GetUnderlyingType(propType) : propType; try { var new_val = Convert.ChangeType(values[count], targetType, null); prop.SetValue(contact, new_val); } catch (InvalidCastException e) { throw new InvalidCastException(e.Message); } } else { continue; } } count++; } _crmContext.Entry(contact).State = EntityState.Modified; } } } else if (action.Type.ToLower() == "delete") { if (contacts != null) { //TODO delete action foreach (var contact in contacts) { _crmContext.Contact.Remove(contact); } } } else if (action.Type.ToLower() == "create") { Contact template = new Contact(); //TODO create action if (action.MetaData == null) { continue; } string[] values = action.Value.Split("_"); string[] fields = action.MetaData.Field.Split("_"); if (values.Length != fields.Length) { throw new Exception(nameof(action)); } int count = 0; foreach (var field in fields) { foreach (var prop in template.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (prop.Name == field) { // FieldInfo fieldInfo = contactType.GetFieldInfo(prop.Name); // fieldInfo.SetValue(null, action.Value); prop.SetValue(template, values[count]); } else { continue; } } count++; } _crmContext.Contact.Add(template); } } try { await _crmContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } //TODO do action depend on prop, val } else if (t.Table.ToLower() == "campaign") { foreach (var action in t.Actions) { var campaigns = _crmContext.Campaign.Where(expression, p).ToList(); // Type campaignType = campaign.GetType(); if (action.Type.ToLower() == "update") { if (campaigns != null) { foreach (var campaign in campaigns) { if (action.MetaData == null) { continue; } string[] values = action.Value.Split("_"); string[] fields = action.MetaData.Field.Split("_"); if (values.Length != fields.Length) { throw new Exception(nameof(action)); } int count = 0; foreach (var field in fields) { foreach (var prop in campaign.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (prop.Name.ToLower() == field.ToLower()) { // FieldInfo fieldInfo = campaignType.GetFieldInfo(prop.Name); // fieldInfo.SetValue(null, action.Value); var propType = prop.PropertyType; var targetType = propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)) ? Nullable.GetUnderlyingType(propType) : propType; try { var new_val = Convert.ChangeType(values[count], targetType, null); prop.SetValue(campaign, new_val); } catch (InvalidCastException e) { throw new InvalidCastException(e.Message); } } else { continue; } } count++; } _crmContext.Entry(campaign).State = EntityState.Modified; } } } else if (action.Type.ToLower() == "delete") { if (campaigns != null) { //TODO delete action foreach (var campaign in campaigns) { _crmContext.Campaign.Remove(campaign); } } } else if (action.Type.ToLower() == "create") { Campaign template = new Campaign(); //TODO create action if (action.MetaData == null) { continue; } string[] values = action.Value.Split("_"); string[] fields = action.MetaData.Field.Split("_"); if (values.Length != fields.Length) { throw new Exception(nameof(action)); } int count = 0; foreach (var field in fields) { foreach (var prop in template.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (prop.Name == field) { prop.SetValue(template, values[count]); } else { continue; } } count++; } _crmContext.Campaign.Add(template); } } try { await _crmContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } //TODO do action depend on prop, val } }