public bool Sync()
        {
            var accounts = _uow.GetRepository <Account>().GetAll().ToList();

            foreach (var account in accounts)
            {
                var cernerSyncedLocations = _uow.GetRepository <Location>().Queryable().Where(x => x.AccountId == account.AccountId && x.ExternalKey3 != null).ToList();
                foreach (var location in cernerSyncedLocations)
                {
                    CernerResult result = SyncToCarner(location.LocationId);
                    try
                    {
                        using (var scope = new TransactionScope())
                        {
                            foreach (var appointment in result.Appointments)
                            {
                                _cernerAppointmentService.CreateAppointment(appointment);
                            }

                            foreach (var patient in result.Patients)
                            {
                                _cernerPatientService.CreatePatient(patient);
                            }
                            scope.Complete();
                        }
                        _cernerAppointmentService.CreateChargeCaptureAppointments(result.Appointments);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
        private CernerResult SyncToCarner(long locationId)
        {
            CernerResult result = new CernerResult();

            var token = new CernerLoginServices(_uow, _fhirConfigurationServices).GetToken(locationId);

            if (token != null)
            {
                var location = _uow.GetRepository <Location>().Find(locationId);

                FhirClient fhirClient = new FhirClient(token.dataEndpoint);
                fhirClient.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
                {
                    e.RawRequest.Headers.Add("Authorization", "Bearer " + token.access_token);
                };

                fhirClient.UseFormatParam  = true;
                fhirClient.PreferredFormat = ResourceFormat.Json;
                List <string> searchCriteria = new List <string>();
                searchCriteria.Add("location=" + location.ExternalKey3);
                searchCriteria.Add("_count=1000");

                if (token.lastSyncDate != null)
                {
                    searchCriteria.Add("date=ge" + ((DateTime)token.lastSyncDate).ToString("yyyy-MM-dd"));
                }
                else
                {
                    //searchCriteria.Add("date=ge" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
                    searchCriteria.Add("date=gt" + DateTime.Now.AddDays(-1200).ToString("yyyy-MM-dd"));
                }
                searchCriteria.Add("date=le" + DateTime.Now.ToString("yyyy-MM-dd"));

                var query  = searchCriteria.ToArray();
                var bundle = fhirClient.Search <Hl7.Fhir.Model.Appointment>(query).Entry.ToList();

                List <CernerAppointment> appointments = new List <CernerAppointment>();
                List <CernerPatient>     patients     = new List <CernerPatient>();

                foreach (var item in bundle)
                {
                    CernerAppointment appointment = new CernerAppointment();
                    var resource = ((Hl7.Fhir.Model.Appointment)item.Resource);

                    appointment.CernerIntegrationId = resource.Id;
                    appointment.AccountId           = _userInfo.AccountId;
                    appointment.AppointmentStatus   = (string)((Hl7.Fhir.Model.Appointment)item.Resource).StatusElement.ObjectValue;
                    var appointmentType = ((Hl7.Fhir.Model.Appointment)item.Resource).Type;
                    foreach (var type in appointmentType.Coding)
                    {
                        appointment.AppointmentTypeCode    = type.Code;
                        appointment.AppointmentTypeDisplay = type.Display;
                    }
                    appointment.Reason            = ((Hl7.Fhir.Model.Appointment)item.Resource).Reason == null ? null : ((Hl7.Fhir.Model.Appointment)item.Resource).Reason.Text;
                    appointment.Description       = ((Hl7.Fhir.Model.Appointment)item.Resource).Description;
                    appointment.DurationInMinutes = ((Hl7.Fhir.Model.Appointment)item.Resource).MinutesDuration == null ? 0 : (int)((Hl7.Fhir.Model.Appointment)item.Resource).MinutesDuration;
                    appointment.Comment           = ((Hl7.Fhir.Model.Appointment)item.Resource).Comment;
                    DateTimeOffset?dateStart = ((Hl7.Fhir.Model.Appointment)item.Resource).Start;
                    DateTimeOffset?dateEnd   = ((Hl7.Fhir.Model.Appointment)item.Resource).End;
                    if (dateStart != null)
                    {
                        appointment.StartDate = ((DateTimeOffset)dateStart).UtcDateTime;
                    }
                    if (dateEnd != null)
                    {
                        appointment.EndDate = ((DateTimeOffset)dateEnd).UtcDateTime;
                    }

                    var participants = ((Hl7.Fhir.Model.Appointment)item.Resource).Participant;
                    foreach (var participant in participants)
                    {
                        if (participant.Actor.Reference != null)
                        {
                            var actor = (participant.Actor.Reference).Split('/');
                            switch (actor[0])
                            {
                            case "Patient":
                                appointment.PatientId = actor[1];
                                var existingPatient = patients.Where(x => x.CernerIntegrationId == appointment.PatientId).FirstOrDefault();
                                if (existingPatient == null)
                                {
                                    var patient = GetPatientById(appointment.PatientId, token);
                                    patients.Add(patient);
                                }
                                break;

                            case "Practitioner":
                                appointment.PractitionerId = actor[1];
                                break;

                            case "Location":
                                appointment.LocationId = actor[1];
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    appointments.Add(appointment);
                }
                result.Appointments = appointments;
                result.Patients     = patients;

                _fhirConfigurationServices.UpdateLastSyncDate(token.endpointId);
            }
            return(result);
        }