public async Task FetchAndUpdateDatabase(DateTime time) { using (DIEMDANHAPIEntities db = new DIEMDANHAPIEntities()) { using (var transaction = db.Database.BeginTransaction()) { try { // IDENTIFY THE NEXT TIME POINT IF SUCCESSS int timePoint = handler.getTimeLines(time); // FETCH API Result dataReceived = await handler.fetchData(time); // int headerIDMin = headerDAO.getFirstSuccessfullyFetch(dataReceived.dateFetching, dataReceived.Session); // headerDAO.Insert(dataReceived); // if (dataReceived.success) { int currenHeaderID = headerDAO.getHeader(dataReceived.dateFetching, dataReceived.Session, dataReceived.actualTimeFetching); if (headerIDMin == -1) { headerIDMin = currenHeaderID; headerDetailDAO.Insert(headerIDMin); } // var listHaveNotAdded = attendanceDAO.getUnExistItemList(dataReceived.data, headerIDMin); List <DiemDanh_NangSuatLaoDong> attendanceList = new List <DiemDanh_NangSuatLaoDong>(); foreach (var item in listHaveNotAdded) { DiemDanh_NangSuatLaoDong ddEntity = new DiemDanh_NangSuatLaoDong(); ddEntity.HeaderID = headerIDMin; ddEntity.MaNV = item.MaNhanVien; ddEntity.ActualHeaderFetched = currenHeaderID; ddEntity.DiLam = true; ddEntity.isFilledFromAPI = true; ddEntity.isChangedManually = false; ddEntity.ThoiGianXuongLo = item.startTime; ddEntity.ThoiGianLenLo = item.endTime; attendanceList.Add(ddEntity); } attendanceDAO.Insert(attendanceList); DateTime nextTimePoint; if (timePoint == 5) { // next 2 AM morning nextTimePoint = new DateTime(time.Year, time.Month, time.Day + 1, 2, 0, 0); } else { nextTimePoint = new DateTime(time.Year, time.Month, time.Day, handler.timelinesHours[timePoint], handler.timelinesMinutes[timePoint], 0); } timer.Interval = nextTimePoint.Subtract(time).Seconds; } else { // 10 minutes each until successfully fetch timer.Interval = 10 * 1000 * 60; } transaction.Commit(); } catch (Exception ex) { WriteToFile(ex.Message); transaction.Rollback(); } } } }