public async Task CommitTestRecord()
        {
            await PopupNavigation.Instance.PopAllAsync();

            UserDialogs.Instance.ShowLoading("Loading...");
            await Task.Delay(300);

            var username = Convert.ToString(Application.Current.Properties["UserName"]);
            var password = Convert.ToString(Application.Current.Properties["PassID"]);

            try
            {
                var response = await new BDIWebServices().LoginUser(new { username = username.Trim(), password = password.Trim() });
                if (response != null)
                {
                    if (!string.IsNullOrEmpty(response.StatusCode))
                    {
                        UserDialogs.Instance.HideLoading();
                        await UserDialogs.Instance.AlertAsync("Sync Failed!");

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.HideLoading();
                if (!string.IsNullOrEmpty(ex.Message) && ex.Message == "User Don't have BDI product")
                {
                    await UserDialogs.Instance.AlertAsync("You Don't have BDI product access. Please contact Admin");
                }
                else
                {
                    await UserDialogs.Instance.AlertAsync("Sync Failed!");
                }
                return;
            }
            UserDialogs.Instance.HideLoading();
            UserDialogs.Instance.ShowLoading("Syncing Data to server...");
            var lstStudents = new List <Students>();

            var selectedRecords = new List <ChildInformationRecord>();

            if (!isIndividual)
            {
                selectedRecords = ChildInformationRecords.Where(p => p.IsSelect).ToList();
            }
            else
            {
                selectedRecords = new List <ChildInformationRecord>();
                selectedRecords.Add(SelectedRecord);
            }

            if (selectedRecords != null && selectedRecords.Any())
            {
                var groupedRecords = selectedRecords;
                if (groupedRecords != null && groupedRecords.Any())
                {
                    var lstSync             = new List <SyncChild>();
                    var orgID               = Convert.ToInt32(Application.Current.Properties["OrgnazationID"]);
                    var researchCodes       = productResearchCodesService.GetResearchCodesByOrg(orgID);
                    var localStudent        = _studentService.GetStudentById(OfflineStudentId);
                    var researchCodesValues = productResearchCodeValuesService.GetProductResearchCodes(OfflineStudentId);
                    var syncChild           = new SyncChild();
                    int addedBy;
                    var isSuccess = int.TryParse(Application.Current.Properties["UserID"].ToString(), out addedBy);
                    if (localStudent != null)
                    {
                        lstStudents.Add(localStudent);
                        localStudent.LocalTestFormIds = string.Join(",", selectedRecords.ToList().Select(p => p.LocalTestInstance));
                        var data       = localStudent;
                        var userRecord = userservice.GetUserByID(addedBy);
                        syncChild.DeviceId = userRecord.DeviceId;
                        lstSync.Add(syncChild);
                        syncChild.SkipUpdate       = localStudent.IsSynced;
                        syncChild.LocalChildUserId = data.OfflineStudentID;
                        syncChild.ChildId          = data.ChildID;
                        if (!string.IsNullOrEmpty(data.UserId))
                        {
                            syncChild.UserId = Convert.ToInt32(data.UserId);
                        }
                        syncChild.OrganizationId = orgID;
                        syncChild.DateOfBirth    = data.Birthdate.Month + "/" + data.Birthdate.Day + "/" + data.Birthdate.Year;
                        syncChild.EnrollmentDate = data.EnrollmentDate == DateTime.MinValue ? null : data.EnrollmentDate.Month + "/" + data.EnrollmentDate.Day + "/" + data.EnrollmentDate.Year;
                        if (!string.IsNullOrEmpty(data.SelectedEthnictyIds))
                        {
                            syncChild.EthnicityId = Convert.ToInt32(data.SelectedEthnictyIds);
                        }
                        syncChild.FirstName            = data.FirstName;
                        syncChild.LastName             = data.LastName;
                        syncChild.MiddleName           = data.MiddleName;
                        syncChild.ParentGuardianEmail1 = data.ParentEmailAddress1;
                        syncChild.ParentGuardianEmail2 = data.ParentEmailAddress2;
                        syncChild.ParentGuardianName1  = data.ParentGuardian1;
                        syncChild.ParentGuardianName2  = data.ParentGuardian2;
                        if (!string.IsNullOrEmpty(data.SelectedLanguageIds))
                        {
                            syncChild.PrimaryLanguageId = Convert.ToInt32(data.SelectedLanguageIds);
                        }
                        if (!string.IsNullOrEmpty(data.SelectedRaceIds))
                        {
                            syncChild.RaceIds = data.SelectedRaceIds.Split(',').Select(p => Convert.ToInt32(p)).ToList();
                        }
                        syncChild.FreeLunch = Convert.ToBoolean(data.IsFreeLunch);
                        if (!string.IsNullOrEmpty(data.SelectedFundingSourceIds))
                        {
                            syncChild.FundingResourceIds = data.SelectedFundingSourceIds.Split(',').Select(p => Convert.ToInt32(p)).ToList();
                        }
                        syncChild.GenderId           = data.Gender;
                        syncChild.Iep                = Convert.ToBoolean(data.IsIEP);
                        syncChild.Ifsp               = Convert.ToBoolean(data.IsIFSP);
                        syncChild.LocationId         = data.SelectedLocationId.Value;
                        syncChild.CreatedDate        = data.updatedOn;
                        syncChild.researchCodeNames  = new List <SyncResearchCodeName>();
                        syncChild.ResearchCodeValues = new List <SyncResearchCodeValue>();
                        if (Convert.ToBoolean(data.IsIEP))
                        {
                            syncChild.IepEligibilityDate = data.IEPEligibilityDate == DateTime.MinValue ? null : data.IEPEligibilityDate.Month + "/" + data.IEPEligibilityDate.Day + "/" + data.IEPEligibilityDate.Year;
                            syncChild.IepExitDate        = data.IEPExitDate == DateTime.MinValue ? null : data.IEPExitDate.Month + "/" + data.IEPExitDate.Day + "/" + data.IEPExitDate.Year;
                        }
                        if (Convert.ToBoolean(data.IsIFSP))
                        {
                            syncChild.IfspEligibilityDate = data.IFSPEligibilityDate == DateTime.MinValue ? null : data.IFSPEligibilityDate.Month + "/" + data.IFSPEligibilityDate.Day + "/" + data.IFSPEligibilityDate.Year;
                            syncChild.IfspExitDate        = data.IFSPExitDate == DateTime.MinValue ? null : data.IFSPExitDate.Month + "/" + data.IFSPExitDate.Day + "/" + data.IFSPExitDate.Year;
                        }

                        if (Convert.ToBoolean(data.IsIEP) || Convert.ToBoolean(data.IsIFSP))
                        {
                            if (!string.IsNullOrEmpty(data.SelectedPrimaryDiagnosesIds))
                            {
                                syncChild.PrimaryDiagnosesId = Convert.ToInt32(data.SelectedPrimaryDiagnosesIds);
                            }
                            if (!string.IsNullOrEmpty(data.SelectedSecondaryDiagnosesIds))
                            {
                                syncChild.SecondaryDiagnosesId = Convert.ToInt32(data.SelectedSecondaryDiagnosesIds);
                            }
                        }

                        foreach (var codes in researchCodes)
                        {
                            syncChild.researchCodeNames.Add(new SyncResearchCodeName()
                            {
                                Name           = codes.ValueName,
                                ResearchCodeId = codes.ResearchCodeId
                            });
                        }

                        foreach (var codevalues in researchCodesValues)
                        {
                            syncChild.ResearchCodeValues.Add(new SyncResearchCodeValue()
                            {
                                ResearchCodeId      = codevalues.ResearchCodeId,
                                ResearchCodeValueId = codevalues.ResearchCodeValueId,
                                Value = codevalues.value
                            });
                        }
                    }
                    syncChild.TestRecords = new List <SyncTestRecord>();
                    foreach (var inneritem in selectedRecords)
                    {
                        var testRecord = clinicalTestFormService.GetStudentTestFormsByID(inneritem.LocalTestInstance);
                        if (testRecord != null)
                        {
                            var newSyncTestRecord = new SyncTestRecord();
                            syncChild.TestRecords.Add(newSyncTestRecord);
                            newSyncTestRecord.AdditionalNotes     = testRecord.additionalNotes;
                            newSyncTestRecord.Notes               = testRecord.notes;
                            newSyncTestRecord.AssessmentId        = testRecord.assessmentId;
                            newSyncTestRecord.CreateDate          = Convert.ToString(testRecord.createDate.Value);
                            newSyncTestRecord.CreatedByUserId     = addedBy;
                            newSyncTestRecord.FormParameters      = testRecord.formParameters;
                            newSyncTestRecord.LocalFormInstanceId = testRecord.LocalTestRecodId;
                            newSyncTestRecord.ContentCategories   = new List <SyncContentCategory>();

                            var records = studentTestFormsService.GetStudentTestForms(testRecord.LocalTestRecodId);
                            if (records != null && records.Any())
                            {
                                foreach (var record in records)
                                {
                                    var newContentCatgory = new SyncContentCategory();
                                    newContentCatgory.ContentCategoryId = record.contentCategoryId;
                                    newContentCatgory.CreateDate        = Convert.ToString(record.createDate.Value);
                                    newContentCatgory.ExaminerId        = record.examinerId.Value;
                                    newContentCatgory.Order             = commonDataService.TotalCategories.FirstOrDefault(p => p.contentCategoryId == record.contentCategoryId).sequenceNo;
                                    newContentCatgory.Notes             = record.Notes;
                                    newContentCatgory.TimeTaken         = record.TimeTaken;
                                    newContentCatgory.RawScore          = record.rawScore;
                                    newContentCatgory.ItemScore         = record.rawScoreEnabled ? 0 : 1;
                                    newContentCatgory.Status            = record.TSOStatus == "Saved" ? 1 : 0;
                                    newContentCatgory.AgeInMonths       = CalculateAgeDiff(lstStudents.FirstOrDefault().Birthdate);
                                    newContentCatgory.TestDate          = record.testDate;
                                    var testformResponse = studentTestFormResponsesService.GetStudentTestFormResponses(testRecord.LocalTestRecodId);
                                    var itemResponse     = testformResponse.FirstOrDefault(p => p.ContentCategoryId == record.contentCategoryId);
                                    if (itemResponse != null)
                                    {
                                        newContentCatgory.ItemLevelResponse           = new SyncItemLevelResponse();
                                        newContentCatgory.ItemLevelResponse.CreatedBy = addedBy;
                                        newContentCatgory.ItemLevelResponse.SectionId = JsonConvert.DeserializeObject <FormJsonClass>(newSyncTestRecord.FormParameters).sectionId;
                                        newContentCatgory.ItemLevelResponse.Response  = itemResponse.Response;
                                        newContentCatgory.ItemLevelResponse.CreatedOn = Convert.ToString(itemResponse.CreatedOn.Value);
                                        newSyncTestRecord.ContentCategories.Add(newContentCatgory);
                                    }
                                }
                            }
                        }
                    }
                    if (lstSync != null && lstSync.Any())
                    {
                        var response = await new BDIWebServices().SyncTestRecords(lstSync, ShowError);
                        if (response != null && response.Any())
                        {
                            foreach (var item in response)
                            {
                                if (item.StatusCode == SyncTestRecordStatusCode.Success)
                                {
                                    clinicalTestFormService.DeleteTestFormByLocalID(item.LocalFormInstanceId);
                                    studentTestFormsService.DeleteAll(item.LocalFormInstanceId);
                                    studentTestFormResponsesService.DeleteAll(item.LocalFormInstanceId);
                                    if (lstStudents.Any(p => p.LocalTestFormIds.Split(',').Contains(item.LocalFormInstanceId + "")))
                                    {
                                        var student = lstStudents.FirstOrDefault(p => p.LocalTestFormIds.Split(',').Contains(item.LocalFormInstanceId + ""));
                                        if (student != null && string.IsNullOrEmpty(student.UserId))
                                        {
                                            student.UserId       = item.ChildUserId.Value.ToString();
                                            student.updatedOn    = DateTime.Now.ToUniversalTime().ToString();
                                            student.updatedOnUTC = DateTime.Now.ToUniversalTime().ToString();
                                            _studentService.Update(student);
                                        }
                                    }
                                    if (item.ResearchCodeValues != null && item.ResearchCodeValues.Any())
                                    {
                                        var student               = lstStudents.FirstOrDefault(p => p.LocalTestFormIds.Split(',').Contains(item.LocalFormInstanceId + ""));
                                        var localCodeValues       = productResearchCodeValuesService.GetProductResearchCodes(student.OfflineStudentID);
                                        var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                                        foreach (var innerItem in localCodeValues)
                                        {
                                            innerItem.ResearchCodeValueId = item.ResearchCodeValues.FirstOrDefault(p => p.ResearchCodeId == innerItem.ResearchCodeId).ResearchCodeValueId;
                                        }
                                        productResearchCodeValuesService.DeleteByStudentId(item.LocalChildUserId);
                                        productResearchCodeValuesService.InsertAll(localCodeValues);
                                    }
                                }
                                else
                                {
                                    if (lstStudents.Any(p => p.LocalTestFormIds.Split(',').Contains(item.LocalFormInstanceId + "")))
                                    {
                                        var student = lstStudents.FirstOrDefault(p => p.LocalTestFormIds.Split(',').Contains(item.LocalFormInstanceId + ""));
                                        if (item.ChildUserId.HasValue)
                                        {
                                            if (student != null && string.IsNullOrEmpty(student.UserId))
                                            {
                                                student.UserId       = item.ChildUserId.Value.ToString();
                                                student.updatedOn    = DateTime.Now.ToUniversalTime().ToString();
                                                student.updatedOnUTC = DateTime.Now.ToUniversalTime().ToString();
                                                _studentService.Update(student);
                                            }
                                        }
                                    }
                                    if (item.ResearchCodeValues != null && item.ResearchCodeValues.Any() && item.ChildUserId.HasValue)
                                    {
                                        var student               = lstStudents.FirstOrDefault(p => p.LocalTestFormIds.Split(',').Contains(item.LocalFormInstanceId + ""));
                                        var localCodeValues       = productResearchCodeValuesService.GetProductResearchCodes(student.OfflineStudentID);
                                        var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                                        foreach (var innerItem in localCodeValues)
                                        {
                                            innerItem.ResearchCodeValueId = item.ResearchCodeValues.FirstOrDefault(p => p.ResearchCodeId == innerItem.ResearchCodeId).ResearchCodeValueId;
                                        }
                                        productResearchCodeValuesService.DeleteByStudentId(item.LocalChildUserId);
                                        productResearchCodeValuesService.InsertAll(localCodeValues);
                                    }
                                    clinicalTestFormService.UpdateSyncStatus((int)item.StatusCode, item.LocalFormInstanceId);
                                }
                            }
                            LoadTestRecordsFromDB(OfflineStudentId);
                            UserDialogs.Instance.HideLoading();
                        }
                    }
                }
            }
        }
예제 #2
0
        public async Task <bool> CheckFirstTimeAndDownload()
        {
            UserDialogs.Instance.ShowLoading("Loading...");
            var username = Convert.ToString(Application.Current.Properties["UserName"]);
            var password = Convert.ToString(Application.Current.Properties["PassID"]);

            try
            {
                var response = await services.LoginUser(new { username = username.Trim(), password = password.Trim() });

                if (response != null)
                {
                    if (!string.IsNullOrEmpty(response.StatusCode))
                    {
                        UserDialogs.Instance.HideLoading();
                        await UserDialogs.Instance.AlertAsync("Download Failed!");

                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.HideLoading();
                if (!string.IsNullOrEmpty(ex.Message) && ex.Message == "User Don't have BDI product")
                {
                    await UserDialogs.Instance.AlertAsync("You Don't have BDI product access. Please contact Admin");
                }
                else
                {
                    await UserDialogs.Instance.AlertAsync("Download Failed!");
                }
                return(false);
            }
            ICommonDataService commonDataService = DependencyService.Get <ICommonDataService>();
            var lstlocalLocations     = default(List <Location>);
            var needtoDeleteLocations = default(List <Location>);

            UserDialogs.Instance.HideLoading();
            await PopupNavigation.Instance.PushAsync(new SyncingPopupView()
            {
                BindingContext = this
            });

            double totalTaskCount      = 11;
            var    percentageCompleted = 100;

            DownloadProgressMessage = "0%";

            var userResponse = _tokenService.GetTokenResposne();
            int uID, organizationID;

            int.TryParse(userResponse.UserID, out uID);
            int.TryParse(userResponse.OrganizationID, out organizationID);

            var contentSyncData      = userSyncService.GetContentSyncData(ContentTypes.Content.ToString());
            var contentImageSyncData = userSyncService.GetContentSyncData(ContentTypes.Images.ToString());
            var userLastSync         = userSyncService.GetUserSyncTable(uID);
            var childRecords         = await services.GetChildRecords(modifiedSince : userLastSync.LastSyncDatetime);

            DownloadProgressMessage = Convert.ToInt32(percentageCompleted / totalTaskCount) + "%";
            totalTaskCount         -= 1;
            if (childRecords != null && childRecords.StatusCode != 0)
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            var exisingRecords = _studentService.GetStudentsByDownloaded(uID);

            if (exisingRecords != null && exisingRecords.Any())
            {
                if (childRecords != null && childRecords.Childrens != null && childRecords.Childrens.Any())
                {
                    var newlyAddedRecords = childRecords.Childrens.Where(p => !exisingRecords.Select(q => q.UserId).Contains(p.ChildUserID)).ToList();
                    if (newlyAddedRecords != null && newlyAddedRecords.Any())
                    {
                        try
                        {
                            var needtoInsert = new List <Students>();
                            GenerateStudentList(newlyAddedRecords, needtoInsert, uID);
                            _studentService.InsertAll(needtoInsert);
                            var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                            foreach (var item in childRecords.Childrens)
                            {
                                if (item.ResearchCodes != null && item.ResearchCodes.Any())
                                {
                                    foreach (var innerItem in item.ResearchCodes)
                                    {
                                        var ProductResearchCodeValues = new ProductResearchCodeValues();
                                        ProductResearchCodeValues.OrganizationId      = organizationID;
                                        ProductResearchCodeValues.value               = innerItem.value;
                                        ProductResearchCodeValues.ResearchCodeValueId = innerItem.ResearchCodeValueId;
                                        ProductResearchCodeValues.ResearchCodeId      = innerItem.ResearchCodeId;
                                        ProductResearchCodeValues.OfflineStudentID    = needtoInsert.FirstOrDefault(p => p.UserId == item.ChildUserID.ToString()).OfflineStudentID;
                                        lstResearchCodeValues.Add(ProductResearchCodeValues);
                                    }
                                }
                            }
                            if (lstResearchCodeValues != null && lstResearchCodeValues.Any())
                            {
                                _productResearchCodeValuesService.InsertAll(lstResearchCodeValues);
                            }
                        }
                        catch (Exception ex)
                        {
                            Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
                        }
                    }

                    var needtoUpdateRecords = exisingRecords.Where(p => childRecords.Childrens.Select(q => q.ChildUserID).Contains(p.UserId)).ToList();
                    if (needtoUpdateRecords != null && needtoUpdateRecords.Any())
                    {
                        foreach (var item in needtoUpdateRecords)
                        {
                            var serverRecord = childRecords.Childrens.FirstOrDefault(p => p.ChildUserID.ToString() == item.UserId);
                            if (serverRecord.isDeleteStatus == 1)
                            {
                                var needtoInsert = new List <Students>();
                                GenerateStudentList(new List <Child>()
                                {
                                    serverRecord
                                }, needtoInsert, uID);
                                needtoInsert.FirstOrDefault().OfflineStudentID = item.OfflineStudentID;
                                _studentService.Update(needtoInsert.FirstOrDefault());
                            }
                            else
                            {
                                DateTime dateTime;
                                DateTime.TryParse(serverRecord.updatedOnUTC, out dateTime);

                                DateTime itemdateTime;
                                DateTime.TryParse(item.updatedOn, out itemdateTime);

                                if (serverRecord != null && dateTime > itemdateTime)
                                {
                                    var needtoInsert = new List <Students>();
                                    GenerateStudentList(new List <Child>()
                                    {
                                        serverRecord
                                    }, needtoInsert, uID);
                                    needtoInsert.FirstOrDefault().OfflineStudentID = item.OfflineStudentID;
                                    _studentService.Update(needtoInsert.FirstOrDefault());
                                    _productResearchCodeValuesService.DeleteByStudentId(item.OfflineStudentID);
                                    var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                                    foreach (var innerItem in serverRecord.ResearchCodes)
                                    {
                                        var ProductResearchCodeValues = new ProductResearchCodeValues();
                                        ProductResearchCodeValues.OrganizationId      = organizationID;
                                        ProductResearchCodeValues.value               = innerItem.value;
                                        ProductResearchCodeValues.ResearchCodeValueId = innerItem.ResearchCodeValueId;
                                        ProductResearchCodeValues.ResearchCodeId      = innerItem.ResearchCodeId;
                                        ProductResearchCodeValues.OfflineStudentID    = needtoInsert.FirstOrDefault(p => p.UserId == serverRecord.ChildUserID.ToString()).OfflineStudentID;
                                        lstResearchCodeValues.Add(ProductResearchCodeValues);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                }
            }
            else
            {
                var studentsToInsert = new List <Students>();
                if (childRecords != null)
                {
                    GenerateStudentList(childRecords.Childrens, studentsToInsert, uID);
                }
                if (studentsToInsert != null && studentsToInsert.Any())
                {
                    try
                    {
                        _studentService.InsertAll(studentsToInsert);
                        var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                        foreach (var childItem in childRecords.Childrens)
                        {
                            if (childItem.ResearchCodes != null && childItem.ResearchCodes.Any())
                            {
                                foreach (var innerItem in childItem.ResearchCodes)
                                {
                                    var ProductResearchCodeValues = new ProductResearchCodeValues();
                                    ProductResearchCodeValues.OrganizationId      = organizationID;
                                    ProductResearchCodeValues.value               = innerItem.value;
                                    ProductResearchCodeValues.ResearchCodeValueId = innerItem.ResearchCodeValueId;
                                    ProductResearchCodeValues.ResearchCodeId      = innerItem.ResearchCodeId;
                                    ProductResearchCodeValues.OfflineStudentID    = studentsToInsert.FirstOrDefault(p => p.UserId == childItem.ChildUserID.ToString()).OfflineStudentID;
                                    lstResearchCodeValues.Add(ProductResearchCodeValues);
                                }
                            }
                        }
                        if (lstResearchCodeValues != null && lstResearchCodeValues.Any())
                        {
                            _productResearchCodeValuesService.InsertAll(lstResearchCodeValues);
                        }
                    }
                    catch (Exception ex)
                    {
                        Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
                    }
                }
            }

            if (childRecords != null && childRecords.ResearchCodes != null && childRecords.ResearchCodes.Any())
            {
                _productResearchCodesService.DeleteAll(organizationID);
                if (childRecords.ResearchCodes != null && childRecords.ResearchCodes.Any())
                {
                    _productResearchCodesService.InsertAll(childRecords.ResearchCodes);
                }
            }
            var locations = await new BDIWebServices().GetLocationRequestModel(uID);

            DownloadProgressMessage = Convert.ToInt32(percentageCompleted / totalTaskCount) + "%";
            totalTaskCount         -= 2;
            if (locations == null || !locations.Any())
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            else
            {
                if (locations != null && locations.Any())
                {
                    var totalLocations = new List <Models.DBModels.Location>();
                    foreach (var item in locations)
                    {
                        var location = new Models.DBModels.Location();
                        location.LocationId       = item.value;
                        location.LocationName     = item.text;
                        location.IsEnabled        = item.enabled;
                        location.DownloadedBy     = uID;
                        location.isDeleted        = item.isDeleted;
                        location.updatedOn        = item.updatedOn;
                        location.ParentLocationId = item.parentLocationID;
                        location.UserId           = uID;
                        totalLocations.Add(location);
                        GenerateSubLocations(item.subItems, totalLocations, 0, uID);
                    }
                    lstlocalLocations = _locationService.GetAllByDownloadedByLocations(uID);
                    _locationService.DeleteByDownloadedBy(uID);
                    needtoDeleteLocations = lstlocalLocations.Where(p => !totalLocations.Select(q => q.LocationId).Contains(p.LocationId)).ToList();
                    _locationService.InsertAll(totalLocations);
                }
            }
            percentageCompleted     = 50;
            totalTaskCount          = 1.5;
            DownloadProgressMessage = (Convert.ToInt32(percentageCompleted / totalTaskCount) + percentageCompleted) + "%";
            totalTaskCount         -= 1;
            var examiners = await new BDIWebServices().GetExaminer(new Models.Requests.StaffRequestModel());

            DownloadProgressMessage = Convert.ToInt32(percentageCompleted / totalTaskCount) + "%";
            totalTaskCount         -= 1;
            if (examiners == null || !examiners.Any())
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            else
            {
                _examinerService.DeleteByDownloadedBy(uID);
                if (examiners != null && examiners.Any())
                {
                    var orgId = Convert.ToInt32(Application.Current.Properties["OrgnazationID"].ToString());
                    foreach (var item in examiners)
                    {
                        item.DownloadedBy   = uID;
                        item.UserID         = KeyEncryption.Decrypt(item.UserID);
                        item.OrganizationId = orgId;
                    }
                    _examinerService.InsertAll(examiners);
                }
                commonDataService.SearchStaffResponseModel = _examinerService.GetExamainer() ?? new List <SearchStaffResponse>();
            }
            var programNotes = await new BDIWebServices().GetProgramNote(organizationID);

            if (programNotes == null)
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            else
            {
                DownloadProgressMessage = "100%";
                _programNoteService.DeleteByDownloadedBy(uID);
                if (programNotes != null && programNotes.Any())
                {
                    var totalProgram = new List <ProgramNoteModel>();
                    foreach (var item in programNotes)
                    {
                        var programNote = new ProgramNoteModel();
                        programNote.LabelId        = item.LabelId;
                        programNote.LabelName      = item.LabelName;
                        programNote.DeleteType     = item.DeleteType;
                        programNote.DownLoadedBy   = uID;
                        programNote.updatedOn      = item.updatedOn;
                        programNote.OrganizationId = item.OrganizationId;
                        totalProgram.Add(programNote);
                    }
                    _programNoteService.InsertAll(totalProgram);
                }
                commonDataService.ProgramNoteModels = _programNoteService.GetProgramNote() ?? new List <ProgramNoteModel>();
            }
            try
            {
                var organizationRecordForms = await services.GetOrgRecordForms();

                _orgRecordFormService.DeleteAll();
                if (organizationRecordForms != null && organizationRecordForms.Any())
                {
                    organizationRecordForms.ForEach((item) =>
                    {
                        item.DownloadedBy   = uID;
                        item.OrganizationId = organizationID;
                    });
                    _orgRecordFormService.Insert(organizationRecordForms);
                }
                commonDataService.OrgRecordFormList = _orgRecordFormService.GetRecordForms() ?? new List <OrganizationRecordForms>();
            }
            catch (Exception ex)
            {
            }
            var localLocations = _locationService.GetLocations();

            if (needtoDeleteLocations != null && needtoDeleteLocations.Any())
            {
                foreach (var item in needtoDeleteLocations)
                {
                    var deletedLocation = lstlocalLocations.FirstOrDefault(p => p.LocationId == item.LocationId);
                    if (deletedLocation != null)
                    {
                        deletedLocation.isDeleted = true;
                    }
                }
                var locationIDs             = needtoDeleteLocations.Select(p => p.LocationId).ToList();
                var locaDownlodedBtStudents = _studentService.GetStudentsByDownloaded(uID);
                if (locaDownlodedBtStudents != null && locaDownlodedBtStudents.Any())
                {
                    foreach (var item in locaDownlodedBtStudents)
                    {
                        if (item.SelectedLocationId.HasValue && locationIDs.Contains(item.SelectedLocationId.Value))
                        {
                            var locationID = CheckRecursiveLOcationsUpdate(item.SelectedLocationId.Value, lstlocalLocations);
                            item.SelectedLocationId = locationID;
                            _studentService.Update(item);
                        }
                    }
                }
            }
            var userpermissions = default(List <string>);

            if (JObject.Parse(_tokenService.GetTokenResposne().Perms).ToObject <Dictionary <int, string> >().ContainsKey(10))
            {
                userpermissions = JObject.Parse(_tokenService.GetTokenResposne().Perms).ToObject <Dictionary <int, string> >().Where(p => p.Key == 10).Select(p => p.Value).ToList();
                foreach (var item in userpermissions)
                {
                    await _userPermissionService.DeleteAllAsync();

                    var allUserPermissionList = new List <Models.DBModels.UserPermissions>();
                    var splitids = item.Split(',').ToList();
                    foreach (var perId in splitids)
                    {
                        var userPermissions = new Models.DBModels.UserPermissions()
                        {
                            UserId       = uID,
                            PermissionId = Convert.ToInt32(perId)
                        };
                        allUserPermissionList.Add(userPermissions);
                    }
                    await _userPermissionService.InsertAllAsync(allUserPermissionList);
                }
            }
            await PopupNavigation.Instance.PopAllAsync();

            var date = DateTime.Now.ToUniversalTime().ToString("s") + "Z";

            userLastSync.LastSyncDatetime = date;
            userSyncService.UpdateUserSync(userLastSync);
            return(true);
        }