Example #1
0
        public async Task GenerateData()
        {
            await Task.Delay(0);

            ProgramNoteModels        = programNoteService.GetProgramNote() ?? new List <ProgramNoteModel>();
            SearchStaffResponseModel = examinerService.GetExamainer() ?? new List <SearchStaffResponse>();
            OrgRecordFormList        = _orgRecordFormService.GetRecordForms() ?? new List <OrganizationRecordForms>();
            if (TotalCategories != null && TotalCategories.Any())
            {
                GenerateBattleCategories();
                GenerateScreenerCategories();
                GenerateAcademicCategories();
            }
        }
Example #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);
        }