예제 #1
0
        private async Task <File> SaveFileAsync(IFormFile file, int userId, int fileType)
        {
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  AnswerFileType : {fileType} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
            var userInfo = await _appDbContext.UserInfos.Include(k => k.User).FirstOrDefaultAsync(k => k.Id == userId);

            var data = new File()
            {
                IdGuid       = Guid.NewGuid(),
                SizeMb       = file.Length.ToFileMB(),
                Name         = file.FileName,
                ProviderName = "SqlProvider",
                ExtraParams  = "",
                Created      = DateTime.UtcNow,
                MimeType     = file.ContentType,
                Modified     = DateTime.UtcNow,
                CreatedBy    = userInfo.Email,
                ModifiedBy   = userInfo.Email
            };

            var savedEntity = (await _appDbContext.Files.AddAsync(data)).Entity;

            if (fileType == (int)ApplicationQuestionType.File)
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  DocFile : {fileType}");
                await UploadIntoFileDbAsync(savedEntity.IdGuid, file);
            }
            else if (fileType == (int)ApplicationQuestionType.VideoAttachment)
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  VideoFile : {fileType}");
                minioAudioVideoUpload(file, savedEntity.IdGuid);
            }
            await _appDbContext.SaveChangesAsync();

            return(savedEntity);
        }
        public async Task <IFileResponse> GetFileAsync(string fileId)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  FileID: {fileId} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");

                var fileDb = await _fileDbContext.FileDB.FirstOrDefaultAsync(k => k.Id == new Guid(fileId));

                if (fileDb == null)
                {
                    return(new FileResponse(ClientMessageConstant.FileNotFound, HttpStatusCode.NotFound));
                }

                var file = await _appDbContext.Files.FirstOrDefaultAsync(k => k.IdGuid == fileDb.Id);

                var model = new FileView()
                {
                    Id            = file.Id,
                    IdGuid        = file.IdGuid,
                    FileBytes     = fileDb.Bytes,
                    Name          = file.Name,
                    CorrelationId = file.CorrelationId,
                    MimeType      = file.MimeType,
                    SizeMb        = file.SizeMb,
                    ExtraParams   = file.ExtraParams
                };

                return(new FileResponse(model));
            }
            catch (Exception e)
            {
                logger.Error(e);
                return(new FileResponse(e));
            }
        }
예제 #3
0
        public async Task <EmailView> SendProgramSubmissionEmailAsync(string toEmail, string programName, string userName)
        {
            EmailView emailResponse = new EmailView();

            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  EmailTo: {toEmail} UserName: {userName} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var emailSetting = await _appDbContext.ApplicationSettings.ToListAsync();

                var appSetting = new AppSettings()
                {
                    SmtpHost     = emailSetting.FirstOrDefault(k => k.Key == "smtpHostName")?.Value,
                    SmtpPassword = emailSetting.FirstOrDefault(k => k.Key == "smtpPassword")?.Value,
                    SmtpPort     = emailSetting.FirstOrDefault(k => k.Key == "smtpPortNumber")?.Value,
                    SmtpUsername = emailSetting.FirstOrDefault(k => k.Key == "smtpUserName")?.Value
                };
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SMTP_PasswordEncrypt: {appSetting.SmtpPassword}");

                appSetting.SmtpPassword = _encryptor.Decrypt(appSetting.SmtpPassword);

                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SMTP_PasswordDecrypt: {appSetting.SmtpPassword}");

                var email = new MailMessage(appSetting.SmtpUsername, toEmail);

                var templateInfo = await _appDbContext.TemplateInfos.Include(k => k.EmailHeaderAndFooterTemplate).FirstOrDefaultAsync(k => k.Id == 3);

                //var otp = GenerateOtp();

                var body = GetProgramSubmissionEnglishContent(userName, programName, templateInfo, email);


                email.Body       = body;
                email.IsBodyHtml = true;
                using (var smtp = new SmtpClient())
                {
                    smtp.Host      = appSetting.SmtpHost;
                    smtp.EnableSsl = true;
                    NetworkCredential networkCred = new NetworkCredential(appSetting.SmtpUsername, appSetting.SmtpPassword);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials           = networkCred;
                    smtp.Port = int.Parse(appSetting.SmtpPort);
                    smtp.Send(email);
                }
                emailResponse.ID      = Guid.NewGuid();
                emailResponse.Result  = true;
                emailResponse.Message = "Email Sent";
                //emailResponse.OTP = otp;

                return(emailResponse);
            }
            catch (Exception e)
            {
                logger.Error(e);
                emailResponse.ID      = Guid.NewGuid();
                emailResponse.Result  = false;
                emailResponse.Message = "Email Not Sent";
                logger.Info(emailResponse);
                return(emailResponse);
            }
        }
예제 #4
0
        public async Task <IReminderResponse> RemoveReminder(int userId, int applicationId, int activityId)
        {
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  userId : {userId} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

            try
            {
                var reminderData = await _appDbContext.Reminders.Where(x => x.UserID == userId && x.ActivityId == activityId && x.ApplicationId == applicationId).FirstOrDefaultAsync();

                var data = false;
                if (reminderData != null)
                {
                    _appDbContext.Reminders.Remove(reminderData);
                    await _appDbContext.SaveChangesAsync();

                    data = true;
                }

                return(new ReminderResponse(data));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        public async Task <IRecommendLeaderResponse> GetRecommendFitListAsync()
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() } UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var RecommendFitList = await _appDbContext.LookupItems.Where(k => k.LookupId == (int)LookupType.Recommendation).OrderBy(k => k.NameEn).ToListAsync();

                var RecommendSourceItemList = await _appDbContext.LookupItems.Where(k => k.LookupId == (int)LookupType.SourceItem).OrderBy(k => k.NameEn).ToListAsync();

                var RecommendStatusItem = await _appDbContext.LookupItems.Where(k => k.LookupId == (int)LookupType.StatusItem).OrderBy(k => k.NameEn).ToListAsync();

                var data = new RecommendationFitDetailsView()
                {
                    RecommendLeaderFitList        = _mapper.Map <List <LookupItemView> >(RecommendFitList),
                    RecommendLeaderSourceItemList = _mapper.Map <List <LookupItemView> >(RecommendSourceItemList),
                    RecommendLeaderStatusItem     = _mapper.Map <List <LookupItemView> >(RecommendStatusItem)
                };

                return(new RecommendLeaderResponse(data));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        public async Task <IPeopleNearByResponse> HideUserLocation(int userId, bool isHideLocation)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input: {userId} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");

                var data = await _appDbContext.UserLocations.FirstOrDefaultAsync(x => x.ProfileID == userId);

                if (data == null)
                {
                    return(new PeopleNearByResponse(ClientMessageConstant.UserNotFound, HttpStatusCode.NotFound));
                }

                if (data != null)
                {
                    data.isHideLocation = isHideLocation;
                    await _appDbContext.SaveChangesAsync();
                }

                var userLocation = _mapper.Map <UserLocationModelView>(data);
                return(new PeopleNearByResponse(userLocation));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        public async Task <EmailView> SendReportProblemEmailAsync(string reportText, string fromEmail, string userName)
        {
            EmailView emailResponse = new EmailView();

            try
            {
                var emailSetting = await _appDbContext.ApplicationSettings.ToListAsync();

                var appSetting = new AppSettings()
                {
                    SmtpHost     = emailSetting.FirstOrDefault(k => k.Key == "smtpHostName")?.Value,
                    SmtpPassword = emailSetting.FirstOrDefault(k => k.Key == "smtpPassword")?.Value,
                    SmtpPort     = emailSetting.FirstOrDefault(k => k.Key == "smtpPortNumber")?.Value,
                    SmtpUsername = emailSetting.FirstOrDefault(k => k.Key == "emailUs")?.Value
                };
                //logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SMTP_PasswordEncrypt: {appSetting.SmtpPassword}");

                appSetting.SmtpPassword = _encryptor.Decrypt(appSetting.SmtpPassword);
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  ToEmail: {appSetting.SmtpUsername}");
                //logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SMTP_PasswordDecrypt: {appSetting.SmtpPassword}");


                fromEmail = fromEmail != null ? fromEmail : appSetting.SmtpUsername;
                var email    = new MailMessage(fromEmail, appSetting.SmtpUsername);
                var template = await _appDbContext.Templates.Where(x => x.SysName == "ProfileCompletenessTemplate").FirstOrDefaultAsync();

                var templateInfo = await _appDbContext.TemplateInfos.Include(k => k.EmailHeaderAndFooterTemplate).Where(x => x.TemplateId == template.Id).FirstOrDefaultAsync();

                var body = GetReportProblemContent(templateInfo, reportText, email, userName);


                email.Body       = body;
                email.IsBodyHtml = true;
                using (var smtp = new SmtpClient())
                {
                    smtp.Host      = appSetting.SmtpHost;
                    smtp.EnableSsl = true;
                    NetworkCredential networkCred = new NetworkCredential(appSetting.SmtpUsername, appSetting.SmtpPassword);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials           = networkCred;
                    smtp.Port = int.Parse(appSetting.SmtpPort);
                    smtp.Send(email);
                }
                emailResponse.ID      = Guid.NewGuid();
                emailResponse.Result  = true;
                emailResponse.Message = "Email Sent";

                return(emailResponse);
            }
            catch (Exception e)
            {
                logger.Error(e);
                emailResponse.ID      = Guid.NewGuid();
                emailResponse.Result  = false;
                emailResponse.Message = "Email Not Sent";
                logger.Info(emailResponse);
                return(emailResponse);
            }
        }
예제 #8
0
        public async Task <IActivityAndChallengesResponse> GetActivityAsync(int profileId, int categoryId, int activityId)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  ProfileId: {profileId} CategoryId: {categoryId} ActivityId: {activityId} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var userActivity = await _appDbContext.InitiativeProfiles.Include(k => k.Initiative)
                                   .Include(m => m.StatusItem).Where(k => k.ProfileId == profileId).ToListAsync();

                if (categoryId == (int)InitiativeType.MyActivity)
                {
                    var userInitiative = userActivity.Select(k =>
                    {
                        var ini = _mapper.Map <InitiativeViewModel>(k.Initiative);
                        ini.InitiativeStatus = _mapper.Map <LookupItemView>(k.StatusItem);
                        return(ini);
                    }).ToList().FirstOrDefault(c => c.Id == activityId);
                    if (userInitiative != null)
                    {
                        return(new ActivityAndChallengesResponse(userInitiative));
                    }
                    else
                    {
                        return(new ActivityAndChallengesResponse(ClientMessageConstant.Deeplink, HttpStatusCode.NotFound));
                    }
                }

                var initiative = await _appDbContext.Initiatives.FirstOrDefaultAsync(k => (k.CategoryId == categoryId || k.InitiativeTypeItemId == categoryId) && k.Id == activityId);

                var initiativeViewModel = _mapper.Map <InitiativeViewModel>(initiative);

                if (initiativeViewModel != null)
                {
                    var reminder = await _appDbContext.Reminders.Where(x => x.UserID == profileId && x.ActivityId == initiativeViewModel.Id && x.ApplicationId == 2).FirstOrDefaultAsync();

                    initiativeViewModel.isReminderSet = reminder != null ? true : false;

                    initiativeViewModel.InitiativeStatus =
                        _mapper.Map <LookupItemView>(userActivity.FirstOrDefault(c => c.InitiativeId == initiativeViewModel.Id)
                                                     ?.StatusItem);
                    if (initiativeViewModel.FileId != new Guid())
                    {
                        var fileDb = await _fileDbContext.FileDB.FirstOrDefaultAsync(k => k.Id == initiativeViewModel.FileId);

                        if (fileDb != null)
                        {
                            var file = await _appDbContext.Files.FirstOrDefaultAsync(k => k.IdGuid == fileDb.Id);

                            initiativeViewModel.FileName = file.Name;
                        }
                    }
                }
                return(new ActivityAndChallengesResponse(initiativeViewModel));
            }
            catch (Exception e)
            {
                logger.Error(e);
                return(new ActivityAndChallengesResponse(e));
            }
        }
예제 #9
0
        public async Task <IUserRecommendationResponse> AddNotificationAsync(int recipientUserID, ActionType actionId, int recommendId, ParentType parentTypeId, int senderUserId, string notifyText)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  userId: {senderUserId} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                //var profileId = userId != senderUserId ? senderUserId : userId;
                var notificationGenericObject = await _mongoDbContext.NotificationGenericObjects.Find(x => x.UserID == recipientUserID).FirstOrDefaultAsync() ??
                                                await AddNotificationObjectAsync(recipientUserID);

                var notificationObj = new Notification
                {
                    ID           = ObjectId.GenerateNewId(),
                    ActionID     = (int)actionId,
                    IsRead       = false,
                    ParentID     = recommendId.ToString(),
                    ParentTypeID = (int)parentTypeId,
                    SenderID     = senderUserId
                };

                notificationGenericObject.Notifications.Add(notificationObj);

                //if (userId != senderUserId)
                //{
                notificationGenericObject.UnseenNotificationCounter += 1;
                var notificationView = _mapper.Map <NotificationView>(notificationObj);
                await FillNotificationUserDetailsAsync(recipientUserID, new List <NotificationView>() { notificationView });

                var deviceIds = await _appDbContext.UserDeviceInfos.Where(k => k.UserId == recipientUserID).Select(k => k.DeviceId).ToListAsync();

                foreach (var deviceId in deviceIds)
                {
                    await _pushNotificationService.SendRecommendPushNotificationAsync(notificationView, notifyText, deviceId);
                }

                logger.Info("Notification sent");
                //}

                await _mongoDbContext.NotificationGenericObjects.ReplaceOneAsync(x => x.UserID == recipientUserID, notificationGenericObject);



                var notificationGenericObjectView = new NotificationGenericObjectView
                {
                    ID     = notificationGenericObject.ID.ToString(),
                    UserID = notificationGenericObject.UserID,
                    UnseenNotificationCounter = notificationGenericObject.UnseenNotificationCounter,
                    NotificationsList         = _mapper.Map <List <NotificationView> >(notificationGenericObject.Notifications)
                };

                return(new UserRecommendationResponse(notificationGenericObjectView));
            }
            catch (Exception e)
            {
                return(new UserRecommendationResponse(e));
            }
        }
예제 #10
0
        public async Task <EmailView> SendReminderEmailAsync(string toEmail, string content, string userName, int daysLeft, DateTime?registrationEndDate)
        {
            EmailView emailResponse = new EmailView();

            try
            {
                var emailSetting = await _appDbContext.ApplicationSettings.ToListAsync();

                var appSetting = new AppSettings()
                {
                    SmtpHost     = emailSetting.FirstOrDefault(k => k.Key == "smtpHostName")?.Value,
                    SmtpPassword = emailSetting.FirstOrDefault(k => k.Key == "smtpPassword")?.Value,
                    SmtpPort     = emailSetting.FirstOrDefault(k => k.Key == "smtpPortNumber")?.Value,
                    SmtpUsername = emailSetting.FirstOrDefault(k => k.Key == "smtpUserName")?.Value
                };
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SMTP_PasswordEncrypt: {appSetting.SmtpPassword}");

                appSetting.SmtpPassword = _encryptor.Decrypt(appSetting.SmtpPassword);

                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SMTP_PasswordDecrypt: {appSetting.SmtpPassword}");

                var email = new MailMessage(appSetting.SmtpUsername, toEmail);

                var templateInfo = await _appDbContext.TemplateInfos.Include(k => k.EmailHeaderAndFooterTemplate).FirstOrDefaultAsync(k => k.Id == 13001);

                var body = GetReminderContent(content, templateInfo, email, userName, daysLeft, registrationEndDate);


                email.Body       = body;
                email.IsBodyHtml = true;
                using (var smtp = new SmtpClient())
                {
                    smtp.Host      = appSetting.SmtpHost;
                    smtp.EnableSsl = true;
                    NetworkCredential networkCred = new NetworkCredential(appSetting.SmtpUsername, appSetting.SmtpPassword);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials           = networkCred;
                    smtp.Port = int.Parse(appSetting.SmtpPort);
                    smtp.Send(email);
                }
                emailResponse.ID      = Guid.NewGuid();
                emailResponse.Result  = true;
                emailResponse.Message = "Email Sent";

                return(emailResponse);
            }
            catch (Exception e)
            {
                logger.Error(e);
                emailResponse.ID      = Guid.NewGuid();
                emailResponse.Result  = false;
                emailResponse.Message = "Email Not Sent";
                logger.Info(emailResponse);
                return(emailResponse);
            }
        }
        public async Task <IAccountResponse> ForgotPass(ForgotPassword view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input : {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var userInfo = await _appDbContext.UserInfos.Include(k => k.User).FirstOrDefaultAsync(x => x.Email == view.Email);

                ViewModels.ValidateOtp validateOtp = new ViewModels.ValidateOtp();
                if (userInfo == null)
                {
                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Success = false,
                        CustomStatusCode = CustomStatusCode.NotRegisteredEmailID,
                        Message = ClientMessageConstant.NotRegisteredEmailId
                    }));
                }
                else
                {
                    var profileInfo = await _appDbContext.Profiles.FirstOrDefaultAsync(x => x.Id == userInfo.Id);

                    var userName = view.LanguageType == LanguageType.EN ? userInfo.User.NameEn : userInfo.User.NameAr;

                    var emailResult = await _emailService.SendResetPasswordEmailAsync(userInfo.Email, userName, view.LanguageType);

                    validateOtp.UserId = userInfo.UserId;
                    validateOtp.Otp    = userInfo.OTP;
                    userInfo.OTP       = emailResult.OTP;
                    userInfo.Modified  = DateTime.Now;
                    _appDbContext.UserInfos.Update(userInfo);
                    await _appDbContext.SaveChangesAsync();



                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Id = userInfo.UserId,
                        FirstName = profileInfo.FirstNameEn,
                        LastName = profileInfo.LastNameEn,
                        Success = true,
                        CustomStatusCode = CustomStatusCode.Success,
                        Message = ClientMessageConstant.Success
                    }));
                }
            }
            catch (System.Exception ex)
            {
                //Message = $"An error occurred when resetting password: {ex.Message}";
                return(new AccountResponse(new ViewModels.UserRegistration
                {
                    Success = false,
                    CustomStatusCode = CustomStatusCode.FunctionalError,
                    Message = ClientMessageConstant.WeAreUnableToProcessYourRequest
                }, ex));
            }
        }
예제 #12
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  DBConnectionString : {_appSettings}");
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                //optionsBuilder.UseSqlServer("Data Source=10.200.2.116;Initial Catalog=GLP_LOPA;Persist Security Info=True;User ID=Sa;Password=Sw0rd@2020");
                optionsBuilder.UseSqlServer(_appSettings);
            }
        }
        public async Task <IProgramResponse> GetReferenceAsync(int profileId, int batchId)
        {
            try
            {
                var userInfo = await _appDbContext.UserInfos.FirstOrDefaultAsync(k => k.Id == profileId);

                if (userInfo == null)
                {
                    return(new ProgramResponse(ClientMessageConstant.ProfileNotExist, HttpStatusCode.NotFound));
                }

                var application = await
                                  _appDbContext.Applications.FirstOrDefaultAsync(k => k.ProfileId == profileId && k.BatchId == batchId);

                if (application == null)
                {
                    return(new ProgramResponse(ClientMessageConstant.FileNotFound,
                                               HttpStatusCode.NotFound));
                }
                var parti = await _appDbContext.ParticipationReferences.FirstOrDefaultAsync(k => k.ApplicationID == application.Id && k.ProfileID == profileId);

                if (parti == null)
                {
                    parti = await GetReferenceAsync(application.Id, batchId, userInfo);

                    application.ParticipationReferenceID = parti.Id;
                    await _appDbContext.SaveChangesAsync();
                }


                application.StatusItemId = (int)ApplicationProgressStatus.Submitted;

                await _appDbContext.SaveChangesAsync();

                var toEmail = await _appDbContext.UserInfos.Where(x => x.UserId == profileId).Select(x => x.Email).FirstOrDefaultAsync();

                var firstName = await _appDbContext.Profiles.Where(k => k.Id == profileId).Select(k => k.FirstNameEn).FirstOrDefaultAsync();

                var lastName = await _appDbContext.Profiles.Where(k => k.Id == profileId).Select(k => k.LastNameEn).FirstOrDefaultAsync();

                var userName = firstName + " " + lastName;
                var batch    = await _appDbContext.Batches.Where(x => x.Id == batchId).FirstOrDefaultAsync();

                var programName = await _appDbContext.Programmes.Where(x => x.Id == batch.ProgrammeId).Select(x => x.TitleEn).FirstOrDefaultAsync();

                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  Sending Program Submission mail to : {toEmail} Program Name : {programName} UserName : {userName} ");
                await _emailService.SendProgramSubmissionEmailAsync(toEmail, programName, userName);

                return(new ProgramResponse(parti.ReferenceNumber));
            }
            catch (Exception e)
            {
                return(new ProgramResponse(e.Message, HttpStatusCode.InternalServerError));
            }
        }
        public async Task <IAccountResponse> ForgotEmailID(ViewModels.ForgotEmail view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input : {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var profileInfo = await _appDbContext.Profiles.FirstOrDefaultAsync(x => x.Eid == view.EmirateID);

                ViewModels.ValidateOtp Votp = new ViewModels.ValidateOtp();
                if (profileInfo == null)
                {
                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Success = false,
                        CustomStatusCode = CustomStatusCode.NotRegisteredEmiratesID,
                        Message = ClientMessageConstant.NotRegisteredEmiratesId
                    }));
                }
                else
                {
                    var userInfo = await _appDbContext.UserInfos.FirstOrDefaultAsync(x => x.UserId == profileInfo.Id);

                    //EMailProvider emailSet = new EMailProvider(_settings.SmtpUsername, _settings.SmtpPassword, _settings.SmtpHost, _settings.SmtpPort);
                    //SendOtpEmail(emailSet, _settings.SmtpUsername, userInfo.Email, userInfo.otp);


                    //Votp.UserId = userInfo.UserId;
                    //Votp.Otp = userInfo.otp;

                    //Message = _settings.Success;
                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Id = userInfo.UserId,
                        FirstName = profileInfo.FirstNameEn,
                        LastName = profileInfo.LastNameEn,
                        Email = userInfo.Email,
                        //UserId = userInfo.UserId,
                        //Otp = userInfo.otp,
                        Success = true,
                        CustomStatusCode = CustomStatusCode.Success,
                        Message = ClientMessageConstant.Success
                    }));
                }
            }
            catch (System.Exception ex)
            {
                //Message = $"An error occurred when resetting password: {ex.Message}";
                return(new AccountResponse(new ViewModels.UserRegistration
                {
                    Success = false,
                    CustomStatusCode = CustomStatusCode.FunctionalError,
                    Message = ClientMessageConstant.WeAreUnableToProcessYourRequest
                }, ex));
            }
        }
        public async Task <IAccountResponse> ResetPassword(ResetPassword view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input : {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");

                var userInfo = await _appDbContext.UserInfos.FirstOrDefaultAsync(x => x.UserId == view.UserId);

                if (userInfo == null)
                {
                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Id = view.UserId,
                        Success = false,
                        CustomStatusCode = CustomStatusCode.UserNotExist,
                        Message = ClientMessageConstant.UserNotFound
                    }));
                }

                var passresult = _hashing.ValidatePassword(view.OldPassword, userInfo.Password);
                if (!passresult)
                {
                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Id = userInfo.UserId,
                        Success = false,
                        CustomStatusCode = CustomStatusCode.PasswordIsWrong,
                        Message = ClientMessageConstant.PasswordIsWrong
                    }));
                }

                userInfo.Password = _hashing.CreateHash(view.NewPassword);
                await _appDbContext.SaveChangesAsync();


                return(new AccountResponse(new ViewModels.UserRegistration
                {
                    Id = userInfo.UserId,
                    Success = true,
                    CustomStatusCode = CustomStatusCode.Success,
                    Message = ClientMessageConstant.PasswordUpdatedSuccessfully
                }));
            }
            catch (System.Exception ex)
            {
                return(new AccountResponse(new ViewModels.UserRegistration
                {
                    Success = false,
                    CustomStatusCode = CustomStatusCode.FunctionalError,
                    Message = ClientMessageConstant.WeAreUnableToProcessYourRequest
                }, ex));
            }
        }
예제 #16
0
        public async Task <IUserRecommendationResponse> ReceiveAllRecommendationAsync(int recipientUserId)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() } UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var data = await _appDbContext.UserRecommendations.Where(x => x.RecipientUserID == recipientUserId && x.isAccepted != true).ToListAsync();

                var recommendDetails = _mapper.Map <List <UserRecommendView> >(data);



                foreach (var item in recommendDetails)
                {
                    var profile = await _appDbContext.Profiles.FirstOrDefaultAsync(k => k.Id == item.SenderUserID);

                    var workExperience = await _appDbContext.ProfileWorkExperiences.Include(k => k.Title)
                                         .Where(k => k.ProfileId == item.SenderUserID).OrderByDescending(y => y.DateFrom).FirstOrDefaultAsync();

                    var user = await _appDbContext.Users.FirstOrDefaultAsync(k => k.Id == item.SenderUserID);

                    item.UserInfo = new PublicProfileView()
                    {
                        Id              = profile.Id,
                        FirstNameAr     = profile.FirstNameAr ?? "",
                        FirstNameEn     = profile.FirstNameEn ?? "",
                        LastNameAr      = profile.LastNameAr ?? "",
                        LastNameEn      = profile.LastNameEn ?? "",
                        SecondNameAr    = profile.SecondNameAr ?? "",
                        SecondNameEn    = profile.SecondNameEn ?? "",
                        ThirdNameAr     = profile.ThirdNameAr ?? "",
                        ThirdNameEn     = profile.ThirdNameEn ?? "",
                        Designation     = workExperience?.Title?.TitleEn ?? "",
                        DesignationAr   = workExperience?.Title?.TitleAr ?? "",
                        UserImageFileId = user?.OriginalImageFileId ?? 0,
                        About           = ""
                    };
                }
                var recommendInfo = new UserRecommendationDetails()
                {
                    RecommendationInfo = recommendDetails
                };


                return(new UserRecommendationResponse(recommendInfo));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(new UserRecommendationResponse(ex));
            }
        }
        public async Task <IReportProblemResponse> ReportProblemAsync(ReportProblemView view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input: {view.ToJsonString()} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var email = await _appDbContext.UserInfos.Where(k => k.UserId == view.UserID).Select(k => k.Email).FirstOrDefaultAsync();

                if (email == null)
                {
                    return(new ReportProblemResponse(ClientMessageConstant.UserNotFound, HttpStatusCode.NotFound));
                }

                var firstName = await _appDbContext.Profiles.Where(k => k.Id == view.UserID).Select(k => k.FirstNameEn).FirstOrDefaultAsync();

                var lastName = await _appDbContext.Profiles.Where(k => k.Id == view.UserID).Select(k => k.LastNameEn).FirstOrDefaultAsync();

                var userName = firstName + " " + lastName;

                var data = new ReportProblem()
                {
                    UserID            = view.UserID,
                    ReportDescription = view.ReportDescription,
                    Created           = DateTime.Now,
                    Modified          = DateTime.Now,
                    CreatedBy         = userName,
                    ModifiedBy        = userName,
                };

                if (view.ReportFile != null)
                {
                    data.ReportFileID = (await SaveFileAsync(view.ReportFile, email)).Id;
                }

                await _appDbContext.ReportProblems.AddAsync(data);

                await _appDbContext.SaveChangesAsync();

                await _emailService.SendReportProblemEmailAsync(view.ReportDescription, email, userName);

                var reportProblem = _mapper.Map <ReportProblemModelView>(data);

                return(new ReportProblemResponse(reportProblem));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        public async Task <IPeopleNearByResponse> AddUpdateUserLocation(UserLocationModel view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input: {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");

                var firstName = await _appDbContext.Profiles.Where(k => k.Id == view.ProfileID).Select(k => k.FirstNameEn).FirstOrDefaultAsync();

                var lastName = await _appDbContext.Profiles.Where(k => k.Id == view.ProfileID).Select(k => k.LastNameEn).FirstOrDefaultAsync();

                var userName = firstName + " " + lastName;

                var data = await _appDbContext.UserLocations.FirstOrDefaultAsync(x => x.ProfileID == view.ProfileID);

                if (data == null)
                {
                    data = new UserLocation()
                    {
                        ProfileID      = view.ProfileID,
                        Latitude       = view.Latitude,
                        Longitude      = view.Longitude,
                        isHideLocation = true,
                        Created        = DateTime.Now,
                        LastUpdated    = DateTime.Now,
                        CreatedBy      = userName,
                        LastUpdatedBy  = userName
                    };

                    await _appDbContext.UserLocations.AddAsync(data);

                    await _appDbContext.SaveChangesAsync();
                }
                else
                {
                    data.Latitude    = view.Latitude;
                    data.Longitude   = view.Longitude;
                    data.LastUpdated = DateTime.Now;
                    await _appDbContext.SaveChangesAsync();
                }

                var userLocation = _mapper.Map <UserLocationModelView>(data);
                return(new PeopleNearByResponse(userLocation));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        public async Task <IResponse <ViewModels.ValidateOtp> > ValidateOtp(ViewModels.ValidateOtp view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input : {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var userInfo = await _appDbContext.UserInfos.FirstOrDefaultAsync
                               (
                    x => x.UserId == view.UserId &&
                    x.OTP == view.Otp);

                if (userInfo == null)
                {
                    return(new OTPResponce(new ViewModels.ValidateOtp
                    {
                        Success = false,
                        CustomStatusCode = CustomStatusCode.OTPExpiredOrInvalid,
                        Message = ClientMessageConstant.OTPExpiredOrInvalid
                    }));
                }

                //userInfo.TokenIsCompleted = true;
                userInfo.IsActive = true;
                userInfo.CanLogin = true;
                userInfo.Modified = DateTime.Now;
                _appDbContext.UserInfos.Update(userInfo);
                await _appDbContext.SaveChangesAsync();

                return(new OTPResponce(new ViewModels.ValidateOtp
                {
                    UserId = view.UserId,
                    Otp = view.Otp,
                    Success = true,
                    CustomStatusCode = CustomStatusCode.Success,
                    Message = ClientMessageConstant.Success
                }));
            }
            catch (System.Exception ex)
            {
                //Message = $"An error occurred when resetting password: {ex.Message}";
                return(new OTPResponce(new ViewModels.ValidateOtp
                {
                    UserId = view.UserId,
                    Otp = view.Otp,
                    Success = false,
                    CustomStatusCode = CustomStatusCode.FunctionalError,
                    Message = ClientMessageConstant.WeAreUnableToProcessYourRequest
                }));
            }
        }
        public async Task <IResponse <ViewModels.ValidateOtp> > ResendOtp(ViewModels.ResendOTP view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input : {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var userInfo = await _appDbContext.UserInfos.Include(k => k.User).FirstOrDefaultAsync(x => x.UserId == view.UserId);

                if (userInfo == null)
                {
                    return(new OTPResponce(new ViewModels.ValidateOtp
                    {
                        UserId = view.UserId,
                        Success = false,
                        CustomStatusCode = CustomStatusCode.UserNotExist,
                        Message = ClientMessageConstant.UserNotFound
                    }));
                }
                var userName = view.LanguageType == LanguageType.EN ? userInfo.User.NameEn : userInfo.User.NameAr;

                var emailResult = view.ResendOtpType == ResendOtpType.ResetPassword
                    ? await _emailService.SendResetPasswordEmailAsync(userInfo.Email, userName, view.LanguageType)
                    : await _emailService.SendActivationEmailAsync(userInfo.Email, userName, view.LanguageType);

                userInfo.OTP      = emailResult.OTP;
                userInfo.Modified = DateTime.Now;
                _appDbContext.UserInfos.Update(userInfo);
                await _appDbContext.SaveChangesAsync();


                return(new OTPResponce(new ViewModels.ValidateOtp
                {
                    UserId = view.UserId,
                    Success = true,
                    CustomStatusCode = CustomStatusCode.Success,
                    Message = ClientMessageConstant.Success
                }));
            }
            catch (System.Exception ex)
            {
                //Message = $"An error occurred when resetting password: {ex.Message}";
                return(new OTPResponce(new ViewModels.ValidateOtp
                {
                    UserId = view.UserId,
                    Success = false,
                    CustomStatusCode = CustomStatusCode.FunctionalError,
                    Message = ClientMessageConstant.WeAreUnableToProcessYourRequest
                }));
            }
        }
        public async Task <IProgramResponse> GetBatchQuestionsAsync(int profileId, int batchId)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  userId: {profileId} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var batchDetails = await _appDbContext.Batches.FirstOrDefaultAsync(k => k.Id == batchId && !k.IsClosed && k.DateRegFrom <= DateTime.Now && k.DateRegTo >= DateTime.Now);

                if (batchDetails == null)
                {
                    return(null);
                }

                var questionGroups = await _appDbContext.QuestionGroupsQuestions.Include(m => m.Group)
                                     .Include(k => k.Question).Include(k => k.Question.QuestionTypeItem).Include(k => k.Question.Options)
                                     .Where(k => k.GroupId == batchDetails.QuestionGroupId).ToListAsync();

                var questions = questionGroups.Select(k => k.Question).ToList();

                var questionViews = _mapper.Map <List <QuestionViewModel> >(questions);

                var application = await
                                  _appDbContext.Applications.FirstOrDefaultAsync(k => k.ProfileId == profileId && k.BatchId == batchId);

                if (application != null)
                {
                    var listdata = await _appDbContext.QuestionAnswers.Include(k => k.AnswerFile).Include(k => k.Questionansweroptions)
                                   .Where(k => k.ProfileId == profileId && k.ApplicationId == application.Id).ToListAsync();

                    var answers = _mapper.Map <List <QuestionAnswerViewModel> >(listdata);
                    foreach (var item in answers)
                    {
                        var options = listdata.FirstOrDefault(a => a.Id == item.Id).Questionansweroptions.ToList();
                        item.MultiSelectedOptionId = options.Select(a => new QuestionAnswerOptionViewModel()
                        {
                            optionID         = a.optionID,
                            QuestionanswerID = a.QuestionanswerID
                        }).ToList();
                    }
                    questionViews.ForEach(k => k.Answered = answers.FirstOrDefault(y => y.QuestionId == k.Id));
                }

                return(new ProgramResponse(questionViews));
            }
            catch (Exception e)
            {
                return(new ProgramResponse(e.Message, HttpStatusCode.InternalServerError));
            }
        }
        public async Task <IProgramResponse> GetAllProgramAsync(int profileId)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  userId: {profileId} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var programs = await _appDbContext.Programmes.Include(m => m.ProgrammeTypeItem).Include(k => k.Batches).ToListAsync();

                var programViews = _mapper.Map <List <ProgramView> >(programs);

                var applications = _mapper.Map <List <ApplicationView> >(await _appDbContext.Applications
                                                                         .Include(k => k.StatusItem).Include(k => k.ReviewStatusItem).Include(k => k.AssessmentItem)
                                                                         .Include(k => k.SecurityItem).Include(k => k.VideoAssessmentStatus)
                                                                         .Where(k => k.ProfileId == profileId).ToListAsync());

                programViews.ForEach(k => k.Applications = applications);


                foreach (var programView in programViews)
                {
                    programView.CompletedUsersList =
                        await GetProgramCompletedUserDetailsAsync(profileId, programView.BatchId ?? 0);

                    var reminder = await _appDbContext.Reminders.Where(x => x.UserID == profileId && x.ActivityId == programView.BatchId && x.ApplicationId == 1).FirstOrDefaultAsync();

                    programView.isReminderSet = reminder != null ? true : false;

                    List <ApplicationReference> _ref = new List <ApplicationReference>();
                    foreach (var item in programView.Applications)
                    {
                        _ref.Add(new ApplicationReference()
                        {
                            ApplicationId   = item.Id,
                            ReferenceNumber = _appDbContext.ParticipationReferences.FirstOrDefault(a => a.ApplicationID != null && a.ApplicationID == item.Id && a.ProfileID == item.ProfileId)?.ReferenceNumber ?? ""
                        });
                        programView.Application_reference = _ref;
                        //item.ReferenceNumber = _appDbContext.ParticipationReferences.FirstOrDefault(a => a.ApplicationID != null && a.ApplicationID == item.Id && a.ProfileID == item.ProfileId).ReferenceNumber ?? "";
                    }
                }

                return(new ProgramResponse(programViews));
            }
            catch (Exception e)
            {
                logger.Error(e);
                return(new ProgramResponse(e.Message, HttpStatusCode.InternalServerError));
            }
        }
        public async Task <IAccountResponse> SetNewPassword(ViewModels.SetNewPassword view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input : {view.ToJsonString()} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var userInfo = await _appDbContext.UserInfos.FirstOrDefaultAsync(x => x.UserId == view.UserId);

                if (userInfo == null)
                {
                    //Message = ClientMessageConstant.UserNotFound);
                    return(new AccountResponse(new ViewModels.UserRegistration
                    {
                        Id = view.UserId,
                        Success = false,
                        CustomStatusCode = CustomStatusCode.UserNotExist,
                        Message = ClientMessageConstant.UserNotFound
                    }));
                }
                ;

                userInfo.Password         = _hashing.CreateHash(view.NewPassword);
                userInfo.TokenIsCompleted = true;
                await _appDbContext.SaveChangesAsync();

                //Message = _settings.Success;
                return(new AccountResponse(new ViewModels.UserRegistration
                {
                    Id = userInfo.UserId,

                    Success = true,
                    CustomStatusCode = CustomStatusCode.Success,
                    Message = ClientMessageConstant.PasswordUpdatedSuccessfully
                }));
            }
            catch (System.Exception ex)
            {
                // TODO logging stuff
                //Message = $"An error occurred when resetting password: {ex.Message}";
                return(new AccountResponse(new ViewModels.UserRegistration
                {
                    Success = false,
                    CustomStatusCode = CustomStatusCode.FunctionalError,
                    Message = ClientMessageConstant.WeAreUnableToProcessYourRequest
                }, ex));
            }
        }
예제 #24
0
        public async Task <IUserRecommendationResponse> ReceiveRecommendationAsync(int recipientUserId, int recommendID)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() } UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var data = await _appDbContext.UserRecommendations.Where(x => x.RecipientUserID == recipientUserId && x.ID == recommendID).FirstOrDefaultAsync();

                //var recommendDetails = _mapper.Map<UserRecommendationModelView>(data);
                var userRecommend = _mapper.Map <UserRecommendationModelView>(data);
                return(new UserRecommendationResponse(userRecommend));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(new UserRecommendationResponse(ex));
            }
        }
        public async Task <IRecommendLeaderResponse> RequestCallbackAsync(RecommendationCallbackView view)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input: {view.ToJsonString()} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var profileId = _appDbContext.RecommandLeaders.Where(x => x.ID == view.RecommendID).Select(x => x.RecommenderProfileID).FirstOrDefault();
                var email     = await _appDbContext.UserInfos.Where(k => k.UserId == profileId).Select(k => k.Email).FirstOrDefaultAsync();

                var firstName = await _appDbContext.Profiles.Where(k => k.Id == profileId).Select(k => k.FirstNameEn).FirstOrDefaultAsync();

                var lastName = await _appDbContext.Profiles.Where(k => k.Id == profileId).Select(k => k.LastNameEn).FirstOrDefaultAsync();

                var userName = firstName + " " + lastName;
                var data     = new RecommendationCallback()
                {
                    RecommendID   = view.RecommendID,
                    FullName      = view.FullName,
                    ContactNumber = view.ContactNumber,
                    Email         = view.Email,
                    Created       = DateTime.Now,
                    Modified      = DateTime.Now,
                    CreatedBy     = profileId != null ? userName : "******",
                    ModifiedBy    = profileId != null ? userName : "******",
                };

                await _appDbContext.RecommendationCallback.AddAsync(data);

                await _appDbContext.SaveChangesAsync();


                await _emailService.SendRequestCallbackEmailAsync(view.FullName, view.Email, view.ContactNumber, email, userName);


                var requestcallback = _mapper.Map <RecommendationCallbackView>(data);
                return(new RecommendLeaderResponse(requestcallback));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        public bool minioAudioVideoUpload(IFormFile formFile, Guid id)
        {
            var appSetting = new MinIoConfig()
            {
                EndPoint    = _minIoConfig.EndPoint,
                AccessKey   = _minIoConfig.AccessKey,
                SecretKey   = _minIoConfig.SecretKey,
                BucketName  = _minIoConfig.BucketName,
                Location    = _minIoConfig.Location,
                MinIoForDev = _minIoConfig.MinIoForDev,
                FilePath    = _minIoConfig.FilePath
            };

            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  EndPoint : {appSetting.EndPoint}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  AccessKey : {appSetting.AccessKey}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SecretKey : {appSetting.SecretKey}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  BucketName : {appSetting.BucketName}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  Location : {appSetting.Location}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  MinIoForDev : {appSetting.MinIoForDev}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  UserIPAddress: { _userIPAddress.GetUserIP().Result }");

            try
            {
                if (appSetting.MinIoForDev != true)
                {
                    var minio = new MinioClient(appSetting.EndPoint, appSetting.AccessKey, appSetting.SecretKey).WithSSL();
                    Run(minio, formFile, appSetting.BucketName, appSetting.Location, id, appSetting.FilePath).Wait();
                    return(true);
                }
                else
                {
                    var minio = new MinioClient(appSetting.EndPoint, appSetting.AccessKey, appSetting.SecretKey);
                    Run(minio, formFile, appSetting.BucketName, appSetting.Location, id, appSetting.FilePath).Wait();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(false);
            }
        }
예제 #27
0
        public async Task <IUserRecommendationResponse> DeleteRecommendationAsync(int recommendID)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input: {recommendID} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var data = await _appDbContext.UserRecommendations.Where(x => x.ID == recommendID).FirstOrDefaultAsync();

                if (data != null)
                {
                    _appDbContext.Remove(data);
                    await _appDbContext.SaveChangesAsync();
                }
                var recommendDetails = _mapper.Map <UserRecommendationModelView>(data);
                return(new UserRecommendationResponse(true));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(new UserRecommendationResponse(ex));
            }
        }
예제 #28
0
        public async Task <IUserRecommendationResponse> SetReadRecommendationAsync(int recommendId, int recipientUserId, bool isread)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  input: {recipientUserId} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

                var data = await _appDbContext.UserRecommendations.Where(x => x.ID == recommendId && x.RecipientUserID == recipientUserId).FirstOrDefaultAsync();

                if (data != null)
                {
                    data.isRead = isread;

                    await _appDbContext.SaveChangesAsync();
                }
                var recommendDetails = _mapper.Map <UserRecommendationModelView>(data);
                return(new UserRecommendationResponse(recommendDetails));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(new UserRecommendationResponse(ex));
            }
        }
        public async Task <IProgramResponse> GetCompletedProgramAsync(int userId)
        {
            try
            {
                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  userId: {userId} UserIPAddress: {  _userIPAddress.GetUserIP().Result }");
                var completedPrograms = await _appDbContext.Applications.Where(k => k.ProfileId == userId && (k.StatusItemId == (int)ApplicationProgressStatus.Accepted || k.StatusItemId == (int)ApplicationProgressStatus.Alumni)).Join(
                    _appDbContext.Batches.Include(m => m.Programme).Include(m => m.Programme.ProgrammeTypeItem),
                    a => a.BatchId, b => b.Id,
                    (a, b) => new CompletedProgramView
                {
                    BatchNumber       = b.Number,
                    BatchYear         = b.Year,
                    Program           = _mapper.Map <ProgramView>(b.Programme),
                    StatusItemId      = a.StatusItemId ?? 0,
                    ProgramTypeLookup = _mapper.Map <LookupItemView>(b.Programme.ProgrammeTypeItem),
                }).ToListAsync();

                return(new ProgramResponse(completedPrograms));
            }
            catch (Exception e)
            {
                return(new ProgramResponse(ClientMessageConstant.WeAreUnableToProcessYourRequest, HttpStatusCode.InternalServerError));
            }
        }
예제 #30
0
        public async Task <List <Reminder> > SendReminder()
        {
            //var reminderList = await _appDbContext.Reminders.ToListAsync();

            //foreach(var item in reminderList)
            //{
            //    if(item.isReminderSent != true)
            //    {
            //        var registrationEndDate = new DateTime?();
            //        if (item.ApplicationId == 1)
            //        {
            //            registrationEndDate = await _appDbContext.Batches.Where(x => x.ProgrammeId == item.ActivityId).OrderByDescending(x => x.DateRegTo).Select(x => x.DateRegTo).FirstOrDefaultAsync();

            //        }
            //        else if (item.ApplicationId == 2)
            //        {
            //            //var activity = await _appDbContext.InitiativeProfiles.Where(x => x.InitiativeId == item.ActivityId && x.ProfileId == item.UserID).FirstOrDefaultAsync();
            //            registrationEndDate = await _appDbContext.Initiatives.Where(x => x.Id == item.ActivityId).Select(x => x.RegistrationEndDate).FirstOrDefaultAsync();
            //        }

            //        var currentDate = DateTime.Now;

            //        var days = ((registrationEndDate - currentDate) / 3).Value.Days;


            //        var reminderSendDate = registrationEndDate - TimeSpan.FromDays(days);
            //        if (days == 0 || reminderSendDate < DateTime.Now)
            //        {
            //            reminderSendDate = DateTime.Now;
            //        }
            //        item.RegistrationEndDate = registrationEndDate;
            //        item.ReminderSendDate = reminderSendDate;

            //        await _appDbContext.SaveChangesAsync();
            //    }


            //}

            var data = await _appDbContext.Reminders.ToListAsync();

            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  data : {data} UserIPAddress: { _userIPAddress.GetUserIP().Result }");

            if (data.Count > 0)
            {
                foreach (var item in data)
                {
                    var userId = item.UserID;
                    var registrationEndDate = item.RegistrationEndDate;
                    var reminderDate        = item.ReminderSendDate;
                    //var content = item.Name;


                    //var currentDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    //var reminderSendDate = DateTime.Parse(reminderDate.ToString("yyyy-MM-dd"));

                    var currentDate      = DateTime.Now.Date;
                    var reminderSendDate = reminderDate.Value.Date;

                    var daysLeft = (registrationEndDate - reminderSendDate).Value.Days;

                    logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  RegistrationEndDate : {reminderSendDate} CurrentDate: {currentDate}");

                    if (reminderSendDate == currentDate && item.isReminderSent != true)
                    {
                        var content = "";
                        if (item.ApplicationId == 1)
                        {
                            var batch = await _appDbContext.Batches.Where(x => x.Id == item.ActivityId).FirstOrDefaultAsync();

                            content = await _appDbContext.Programmes.Where(x => x.Id == batch.ProgrammeId).Select(x => x.TitleEn).FirstOrDefaultAsync();
                        }
                        else if (item.ApplicationId == 2)
                        {
                            content = await _appDbContext.Initiatives.Where(x => x.Id == item.ActivityId).Select(x => x.TitleEn).FirstOrDefaultAsync();
                        }
                        else if (item.ApplicationId == 3)
                        {
                            content = await _appDbContext.Events.Where(x => x.Id == item.ActivityId).Select(x => x.TextEn).FirstOrDefaultAsync();
                        }


                        var email = await _appDbContext.UserInfos.Where(k => k.UserId == userId).Select(k => k.Email).FirstOrDefaultAsync();

                        var firstName = await _appDbContext.Profiles.Where(k => k.Id == userId).Select(k => k.FirstNameEn).FirstOrDefaultAsync();

                        var lastName = await _appDbContext.Profiles.Where(k => k.Id == userId).Select(k => k.LastNameEn).FirstOrDefaultAsync();

                        var userName  = firstName + " " + lastName;
                        var deviceIds = await _appDbContext.UserDeviceInfos.Where(k => k.UserId == userId).Select(k => k.DeviceId).ToListAsync();

                        logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  Sending reminder mail to : {email}");

                        if (item.ApplicationId != 3)
                        {
                            await _emailService.SendReminderEmailAsync(email, content, userName, daysLeft, registrationEndDate);
                        }

                        if (deviceIds.Count > 0)
                        {
                            foreach (var deviceId in deviceIds)
                            {
                                logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  Sending reminder push notification to User : {userId} and Device ID: {deviceId} ");
                                await _pushNotificationService.SendReminderPushNotificationAsync(content, deviceId, daysLeft, registrationEndDate, item.ApplicationId);
                            }
                            logger.Info("Notification sent");
                        }
                        item.isReminderSent = true;
                        await _appDbContext.SaveChangesAsync();
                    }
                }
            }

            return(data);
        }