none
Can't get the current LoginTime and LogOutTime for IdentityServer RRS feed

  • Question

  • Hi All,

    When I implement my code with the Interface for Identity Server to get the  <g class="gr_ gr_18 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="18" id="18">loginTime</g> and <g class="gr_ gr_19 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="19" id="19">logOutTime</g> and it can't get the current <g class="gr_ gr_20 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="20" id="20">loginTime</g> and <g class="gr_ gr_27 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="27" id="27">logOutTime</g>

    here is my code:
    UserInfoService

            public async Task UpdateLoginTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.Where(x => x.Id == userId).FirstOrDefault();
                user.LoginTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            public async Task UpdateLogOutTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.Where(x => x.Id == userId).FirstOrDefault();
                user.LogoutTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            Task<UserInfo> IUserInfoService.UpdateLoginTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }
    
            public Task<UserInfo> UpdateLogoutTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }

    and IUserServiceInfo.cs

    Task<UserInfo> UpdateLoginTimeAsync(string userId);
    
    Task<UserInfo> UpdateLogoutTimeAsync(string userId);
    How to get the current <g class="gr_ gr_35 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="35" id="35">LoginTime</g> and <g class="gr_ gr_36 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="36" id="36">logoutTime</g>? 

    Thank for the help.


    • Edited by eng teongMVP Monday, January 21, 2019 11:33 AM remove the html inline
    Monday, January 21, 2019 8:21 AM

All replies

  • Hi,

    first I would do this little change(but you don't have to):

            public async Task UpdateLoginTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.FirstOrDefault(x => x.Id == userId);
                user.LoginTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            public async Task UpdateLogOutTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.FirstOrDefault(x => x.Id == userId);
                user.LogoutTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            Task<UserInfo> IUserInfoService.UpdateLoginTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }
    
            public Task<UserInfo> UpdateLogoutTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }

    Can you show us the datatype of _dbIdentity, please? Is it UserInfo? If it is a custom class, can you show us the code or at least an interface?

    Where is your breakpoint when you see this values?

    Greetings, Chris

    Monday, January 21, 2019 11:22 PM
  • Hi,

    first I would do this little change(but you don't have to):

            public async Task UpdateLoginTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.FirstOrDefault(x => x.Id == userId);
                user.LoginTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            public async Task UpdateLogOutTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.FirstOrDefault(x => x.Id == userId);
                user.LogoutTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            Task<UserInfo> IUserInfoService.UpdateLoginTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }
    
            public Task<UserInfo> UpdateLogoutTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }

    Can you show us the datatype of _dbIdentity, please? Is it UserInfo? If it is a custom class, can you show us the code or at least an interface?

    Where is your breakpoint when you see this values?

    Greetings, Chris

    Hi Chris,
    Here is the full code:
    using Community.Constant;
    using Community.Data.CommonDataTypes;
    using Community.Data.Contexts;
    using Community.Data.Entities.Companies.ViewModels;
    using Community.Data.Entities.Emails.ViewModels;
    using Community.Data.Entities.Users;
    using Community.Data.Entities.Users.ViewModels;
    using Community.Service.Companies;
    using Community.Service.MailChimps;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Threading.Tasks;
    
    namespace Community.Service.Users
    {
        public class UserInfoService : IUserInfoService
        {
            private readonly IConfiguration _configuration;
            private readonly xxxDbContext _dbIdentity;
            private readonly ICompanyInfoService _companyInfoService;
            private readonly IMailChimpService _mailChimpService;
    
            public UserInfoService(IConfiguration configuration, HaulioIdentityDbContext dbIdentity, ICompanyInfoService companyInfoService,
                IMailChimpService mailChimpService)
            {
                _configuration = configuration;
                _dbIdentity = dbIdentity;
                _companyInfoService = companyInfoService;
                _mailChimpService = mailChimpService;
            }
    
            public CompanyRoleViewModel GetCompanyRole()
            {
                CompanyRoleViewModel companyRoleViewModel = new CompanyRoleViewModel();
                companyRoleViewModel.EmailTypes = _dbIdentity.AspNetModule.Where(x => x.Type == (int)RoleModuleType.Email)
                           .Select(r => new EmailTypeViewModel
                           {
                               Id = r.Id,
                               Name = r.Name,
                               Module = r.Module,
                               Section = r.Seciton,
                               Checked = false,
                               Type = r.Type
                           }
                           )
                           .ToList();
    
                return companyRoleViewModel;
            }
    
            public async Task<IEnumerable<CompanyRoleViewModel>> GetAllCompanyRolesAsync(long companyID)
            {
                if (_dbIdentity.Roles.Count() > 0)
                {
                    var _roles = await _dbIdentity.Roles
                        .Include(c => c.AspNetRoleModule)
                        .Where(x => x.CompanyId == companyID)
                        .Select(r => new CompanyRoleViewModel
                        {
                            RoleId = r.Id,
                            RoleName = r.Name
                        }
                      ).ToListAsync();
    
                    foreach (CompanyRoleViewModel companyRole in _roles)
                    {
                        companyRole.EmailTypes = await _dbIdentity.AspNetModule.Where(x => x.Type == (int)RoleModuleType.Email)
                            .Select(r => new EmailTypeViewModel
                            {
                                Id = r.Id,
                                Name = r.Name,
                                Module = r.Module,
                                Section = r.Seciton,
                                Checked = (_dbIdentity.AspNetRoleModule.Where(x => x.ApplicationRoleId == companyRole.RoleId && x.AspNetModuleId == r.Id).Count() != 0) ? true : false,
                                Type = r.Type
                            }
                            )
                            .ToListAsync();
                    }
    
                    return _roles;
                }
                else
                {
                    IEnumerable<CompanyRoleViewModel> _role = new List<CompanyRoleViewModel>();
                    return _role;
                }
    
            }
    
            public async Task<CompanyRoleViewModel> GetCompanyRoleAsync(string companyRoleId)
            {
                var selectedRole = await _dbIdentity.Roles
                    .Where(r => r.Id == companyRoleId)
                    .Select(r => new CompanyRoleViewModel
                    {
                        RoleId = r.Id,
                        RoleName = r.Name
                    }
                ).FirstOrDefaultAsync();
    
    
    
    
                selectedRole.EmailTypes = await _dbIdentity.AspNetModule.Where(x => x.Type == (int)RoleModuleType.Email)
                          .Select(r => new EmailTypeViewModel
                          {
                              Id = r.Id,
                              Name = r.Name,
                              Module = r.Module,
                              Section = r.Seciton,
                              Checked = (_dbIdentity.AspNetRoleModule.Where(x => x.ApplicationRoleId == selectedRole.RoleId && x.AspNetModuleId == r.Id).Count() != 0) ? true : false,
                              Type = r.Type
                          }
                          )
                          .ToListAsync();
    
                return selectedRole;
    
            }
    
            public async Task<ServiceSingleRecordInsertOrUpdateResponse> CreateCompanyRoleAsync(CompanyRoleViewModel model, long companyId)
            {
                var newCompanyRole = new ApplicationRole
                {
                    Name = model.RoleName,
                    CompanyId = companyId
                };
    
                await _dbIdentity.Roles.AddAsync(newCompanyRole);
    
                foreach (EmailTypeViewModel email in model.EmailTypes)
                {
                    if (email.Checked)
                    {
                        AspNetModule selectedEmailModule = _dbIdentity.AspNetModule.Where(x => x.Id == email.Id).FirstOrDefault();
    
                        await _dbIdentity.AspNetRoleModule.AddAsync(new AspNetRoleModule
                        {
                            AspNetModuleId = selectedEmailModule.Id,
                            ApplicationRoleId = newCompanyRole.Id
                        });
                    }
                }
    
                await _dbIdentity.SaveChangesAsync();
    
                return new ServiceSingleRecordInsertOrUpdateResponse { RecordCode = newCompanyRole.Id, IsActionSuccessful = true, ErrorMessage = null };
            }
    
            public async Task<ServiceSingleRecordInsertOrUpdateResponse> UpdateCompanyRoleAsync(CompanyRoleViewModel model)
            {
                var selectedCompanyRole = await _dbIdentity.Roles.Where(r => r.Id == model.RoleId).FirstOrDefaultAsync();
                selectedCompanyRole.Name = model.RoleName;
    
                _dbIdentity.Roles.Update(selectedCompanyRole);
    
                _dbIdentity.AspNetRoleModule.RemoveRange(_dbIdentity.AspNetRoleModule.Where(x => x.ApplicationRoleId == selectedCompanyRole.Id).ToList());
    
                await _dbIdentity.SaveChangesAsync();
    
                foreach (EmailTypeViewModel email in model.EmailTypes)
                {
                    if (email.Checked)
                    {
                        AspNetModule selectedEmailModule = _dbIdentity.AspNetModule.Where(x => x.Id == email.Id).FirstOrDefault();
    
                        await _dbIdentity.AspNetRoleModule.AddAsync(new AspNetRoleModule
                        {
                            AspNetModuleId = selectedEmailModule.Id,
                            ApplicationRoleId = selectedCompanyRole.Id
                        });
                    }
                }
    
                await _dbIdentity.SaveChangesAsync();
                return new ServiceSingleRecordInsertOrUpdateResponse { RecordCode = model.RoleId, IsActionSuccessful = true, ErrorMessage = null };
            }
    
            public async Task UpdateLoginTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.Where(x => x.Id == userId).FirstOrDefault();
                user.LoginTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
            
    
            public async Task UpdateLogOutTimeAsync(string userId)
            {
                var user = _dbIdentity.Users.Where(x => x.Id == userId).FirstOrDefault();
                user.LogoutTime = DateTime.Now;
                _dbIdentity.Users.Update(user);
                await _dbIdentity.SaveChangesAsync();
            }
    
            public async Task ApproveUserAccountsOfCompanyAsync(long companyId)
            {
                var companyInfo = await _companyInfoService.RetrieveCompanyAsync(companyId);
    
                var allUnapprovedUsersOfCompanies = await _dbIdentity.Users
                    .Where(u => u.CompanyId == companyId && !u.EmailConfirmed)
                    .ToListAsync();
    
                foreach (var user in allUnapprovedUsersOfCompanies)
                {
                    user.EmailConfirmed = true;
    
                    //add user as subscriber to mailchimp
                    try
                    {
                        await _mailChimpService.AddNewSubscriberAsync(user.Email, companyInfo.CompanyName, companyInfo.CompanyType);
                    }
                    catch (Exception) { }
                }
    
                await _dbIdentity.SaveChangesAsync();
            }
    
            public async Task<ServiceStatusResponse> DeleteUserAsync(string userId)
            {
                var user = await _dbIdentity.Users.FirstOrDefaultAsync(q => q.Id == userId);
                if (user == null) return new ServiceStatusResponse { IsActionSuccessful = false, Message = "User record is not found." };
    
                user.Status = false;
                user.UserName = $"{user.UserName}_{DateTime.Now.ToString("yyyyMMddhhss")}";
                user.PhoneNumber = user.UserName;
                user.NormalizedUserName = user.UserName;
    
                await _dbIdentity.SaveChangesAsync();
    
                return new ServiceStatusResponse { IsActionSuccessful = true, Message = "User record is deleted successfully." };
            }
    
            public async Task<int> RetrieveNumberOfUsersAsync()
            {
                return await _dbIdentity.Users.CountAsync();
            }
    
            public async Task<IEnumerable<UserInfo>> RetrieveAllUsersAsync(bool includingInactive = false)
            {
                var users = await _dbIdentity.Users
                    .Where(ei => (!includingInactive && ei.Status) || includingInactive)
                    .ToListAsync();
    
                var companies = await _companyInfoService.RetrieveAllCompaniesAsync();
    
                var userInfos = new List<UserInfo>();
                foreach (var user in users)
                {
                    var userInfo = await GetUserInfoWithoutCompanyInfoAsync(user);
    
                    var userCompany = companies.FirstOrDefault(c => c.CompanyId == user.CompanyId);
    
                    if (userCompany != null)
                    {
                        userInfo.CompanyName = userCompany.CompanyName;
                        userInfo.CompanyTypeId = userCompany.CompanyType;
                        userInfo.CompanyType = userCompany.CompanyTypeName;
                        userInfo.CompanyBrandAbbreviation = userCompany.BrandAbbreviation;
                        userInfo.CompanyStatus = userCompany.Status;
                        userInfo.CompanyVerified = userCompany.IsVerified;
                    }
    
                    userInfos.Add(userInfo);
                }
    
                return userInfos;
            }
    
            public async Task<string> GenerateCsvContentForAllUsersAsync(bool includingInactive)
            {
                string output = "";
    
                var users = await _dbIdentity.Users
                    .Where(u => (!includingInactive && u.Status) || includingInactive)
                    .OrderBy(u => u.Email)
                    .ToListAsync();
    
                var companies = await _companyInfoService.RetrieveAllCompaniesAsync();
    
                var userInfos = new List<UserInfo>();
                foreach (var user in users)
                {
                    var userInfo = await GetUserInfoWithoutCompanyInfoAsync(user);
    
                    var userCompany = companies.FirstOrDefault(c => c.CompanyId == user.CompanyId);
    
                    if (userCompany != null)
                    {
                        userInfo.CompanyName = userCompany.CompanyName;
                        userInfo.CompanyTypeId = userCompany.CompanyType;
                        userInfo.CompanyType = userCompany.CompanyTypeName;
                        userInfo.CompanyBrandAbbreviation = userCompany.BrandAbbreviation;
                        userInfo.CompanyStatus = userCompany.Status;
                        userInfo.CompanyVerified = userCompany.IsVerified;
                    }
    
                    userInfos.Add(userInfo);
                }
    
                output += $",Email,User ID,Name,Phone,Company,Company Type,Company Status,Role(s),Status,Created At" + Environment.NewLine;
    
                int count = 0;
                foreach (var userInfo in userInfos)
                {
                    string companyStatus = "";
                    if (userInfo.CompanyStatus)
                    {
                        if (userInfo.CompanyVerified)
                        {
                            companyStatus = "Active";
                        }
                        else
                        {
                            companyStatus = "Pending Approval";
                        }
                    }
                    else
                    {
                        companyStatus = "Deactivated";
                    }
    
                    string userStatus = "";
                    if (userInfo.Status)
                    {
                        if (userInfo.EmailConfirmed)
                        {
                            userStatus = "Active";
                        }
                        else
                        {
                            userStatus = "Pending Approval";
                        }
                    }
                    else
                    {
                        userStatus = "Deactivated";
                    }
    
                    string createdAt = "";
                    if (userInfo.CreatedAt.Year != 0001)
                    {
                        createdAt = userInfo.CreatedAt.ToString(Constants.DateOnlyFormat);
                    }
    
                    output += $"{ ++count },{ userInfo.Email },{ userInfo.Id },{ userInfo.FullName },{ userInfo.PhoneNumber }," +
                            $"{ userInfo.CompanyName },{ userInfo.CompanyType },{ companyStatus }," +
                            $"\"{ string.Join(",", userInfo.Roles).Replace('"', '\'') }\",{ userStatus },{ createdAt }" + Environment.NewLine;
                }
    
                return output;
            }
    
            public async Task<UserInfo> RetrieveUserInfoWithoutCompanyByPhoneNumberAsync(string phoneNumber)
            {
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Status && u.PhoneNumber == phoneNumber);
    
                if (selectedUser == null) return null;
    
                return await GetUserInfoWithoutCompanyInfoAsync(selectedUser);
            }
    
            public async Task<UserInfo> RetrieveUserInfoAsync(string userId)
            {
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Id == userId);
    
                return await GetUserInfoAsync(selectedUser);
            }
    
            public async Task<UserInfo> RetrieveUserInfoByEmailAsync(string userEmail)
            {
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Email == userEmail);
    
                return await GetUserInfoAsync(selectedUser);
            }
    
            public async Task<ServiceStatusResponse<UserInfo>> RetrieveUserInfoByPhoneNumberAsync(string phoneNumber)
            {
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Status && u.PhoneNumber == phoneNumber);
    
                if (selectedUser == null) return new ServiceStatusResponse<UserInfo> { IsActionSuccessful = false, Message = "User record is not found or User account was deactivated so he/she could not log in." };
    
                var user = await GetUserInfoAsync(selectedUser);
    
                return new ServiceStatusResponse<UserInfo> { IsActionSuccessful = true, Data = user };
            }
    
            public async Task<string> RetrieveUserFullNameByEmailAsync(string userEmail)
            {
                return await _dbIdentity.Users
                    .Where(u => u.Email == userEmail)
                    .Select(q => q.FullName)
                    .FirstOrDefaultAsync();
            }
    
            public async Task<CompanyProfileManageViewModel> RetrieveUserCompanyInfoByEmailAsync(string userEmail)
            {
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Email == userEmail);
    
                return await GetCompanyInfoOfUserAsync(selectedUser.CompanyId);
            }
    
            public async Task<IEnumerable<UserInfo>> RetrieveInfoOfAllUsersInCompanyAsync(long companyId)
            {
                var allUsersInCompany = await _dbIdentity.Users
                    .Where(u => u.CompanyId == companyId)
                    .ToListAsync();
    
                var infoOfAllUsersInCompany = new List<UserInfo>();
    
                foreach (var user in allUsersInCompany)
                {
                    infoOfAllUsersInCompany.Add(await GetUserInfoAsync(user));
                }
    
                return infoOfAllUsersInCompany;
            }
    
            //retrieve all user emails of selected company 20180123
            public async Task<string[]> RetrieveEmailsOfAllUsersInCompanyAsync(long companyId)
            {
                var allUserEmailsInCompany = await _dbIdentity.Users
                    .Where(u => u.CompanyId == companyId)
                    .Select(x => x.Email)
                    .ToArrayAsync();
    
                return allUserEmailsInCompany;
            }
            public async Task<long> RetrieveCompanyIdByEmailAsync(string userEmail)
            {
                return await _dbIdentity.Users
                    .Where(u => u.Email == userEmail)
                    .Select(q => q.CompanyId).FirstOrDefaultAsync();
            }
    
            public async Task<List<UserIdEmailViewModel>> RetrieveIdEmailOfAllUsersInCompanyAsync(long companyId)
            {
                return await _dbIdentity.Users
                    .Where(u => u.CompanyId == companyId)
                    .Select(x => new UserIdEmailViewModel { Id = x.Id, Email = x.Email })
                    .ToListAsync();
            }
    
            public async Task<List<UserIdEmailFullNameViewModel>> RetrieveIdEmailFullNameOfAllUsersAsync(bool includingInactive = false)
            {
                return await _dbIdentity.Users
                    .Where(ei => (!includingInactive && ei.Status) || includingInactive)
                    .Select(x => new UserIdEmailFullNameViewModel { Id = x.Id, Email = x.Email, FullName = x.FullName })
                    .ToListAsync();
            }
    
            public async Task<IEnumerable<UserInfo>> RetrieveInfoOfAllSuperUsersAsync()
            {
                var allUsersWithoutCompanyId = await _dbIdentity.Users
                    .Where(u => u.CompanyId == 0)
                    .ToListAsync();
    
                var infoOfAllSuperUsers = new List<UserInfo>();
    
                foreach (var user in allUsersWithoutCompanyId)
                {
                    string[] userRoles = await GetRolesOfUserAsync(user.Id);
    
                    if (userRoles.Contains(Roles.SuperUser))
                    {
                        infoOfAllSuperUsers.Add(
                            new UserInfo()
                            {
                                Id = user.Id,
                                Status = user.Status,
                                FullName = user.FullName,
                                Email = user.Email,
                                PhoneNumber = user.PhoneNumber,
                                CompanyName = Constants.NotApplicable,
                                CompanyType = Constants.NotApplicable,
                                Roles = userRoles
                            });
                    }
    
    
                }
    
                return infoOfAllSuperUsers;
            }
    
            public async Task<bool> SubmitNewUserAccountCreationRequest(NewUserAccountCreationRequestViewModel model, string createdBy)
            {
                try
                {
                    await _dbIdentity.NewUserAccountCreationRequests.AddAsync(new NewUserAccountCreationRequest
                    {
                        Email = model.Email,
                        FullName = model.FullName,
                        CompanyId = model.CompanyId,
                        PhoneNumber = model.PhoneNumber,
                        CreatedBy = createdBy,
                        UpdatedBy = createdBy
                    });
    
                    await _dbIdentity.SaveChangesAsync();
    
                    string url = $"{_configuration["AppSettings:HaulioIdentityServerUrl"]}/Account/RegisterUserBySuperUser?newUserEmail={ model.Email }";
    
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.AutomaticDecompression = DecompressionMethods.GZip;
    
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        var output = reader.ReadToEnd();
    
                        await ApproveUserAccountsOfCompanyAsync(model.CompanyId);
                    }
    
                    return true;
                }
                catch (Exception) { }
    
                return false;
            }
    
            public async Task<NewUserAccountCreationRequest> RetrieveNewUserAccountCreationRequestAsync(string userEmail)
            {
                return await _dbIdentity.NewUserAccountCreationRequests
                    .FirstOrDefaultAsync(r => r.Status && r.Email == userEmail && !r.IsDone);
            }
    
            public async Task<bool> SetUserAccountCreationRequestAsDoneAsync(string userEmail)
            {
                try
                {
                    var selectedRequest = await _dbIdentity.NewUserAccountCreationRequests
                        .FirstOrDefaultAsync(r => r.Email == userEmail);
    
                    selectedRequest.IsDone = true;
    
                    await _dbIdentity.SaveChangesAsync();
    
                    return true;
                }
                catch (Exception) { }
    
                return false;
            }
    
            public async Task<ServiceSingleRecordInsertOrUpdateResponse> AttachUserToAnotherCompany(string currentUserId, long currentCompanyId, long targetCompanyId)
            {
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Id == currentUserId);
    
                string[] userRoles = await GetRolesOfUserAsync(selectedUser.Id);
    
                var targetCompany = await _companyInfoService.RetrieveCompanyAsync(targetCompanyId);
    
                if (targetCompany == null)
                {
                    return new ServiceSingleRecordInsertOrUpdateResponse
                    {
                        IsActionSuccessful = false,
                        ErrorMessage = "You are not allowed to attach to this company because it does not exist."
                    };
                }
    
                if (userRoles.Contains(Roles.SuperUser) && selectedUser.CompanyId == currentCompanyId && selectedUser.BeforeSpyingOriginalCompanyId == null)
                {
                    selectedUser.CompanyId = targetCompanyId;
                    selectedUser.BeforeSpyingOriginalCompanyId = currentCompanyId;
    
                    await _dbIdentity.SaveChangesAsync();
    
                    return new ServiceSingleRecordInsertOrUpdateResponse { RecordCode = targetCompany.CompanyName, IsActionSuccessful = true, ErrorMessage = null };
                }
    
                return new ServiceSingleRecordInsertOrUpdateResponse
                {
                    IsActionSuccessful = false,
                    ErrorMessage = "You are not allowed to attach to this company because you are not Super User or you do not belong to your current company. Please retry."
                };
            }
    
            public async Task<ServiceSingleRecordInsertOrUpdateResponse> DetachUserFromCompanyBackToOriginalCompany(string currentUserId, long currentCompanyId, string currentCompanyName)
            {
    
                var selectedUser = await _dbIdentity.Users
                    .FirstOrDefaultAsync(u => u.Id == currentUserId);
    
                if (selectedUser.BeforeSpyingOriginalCompanyId == null)
                {
                    return new ServiceSingleRecordInsertOrUpdateResponse
                    {
                        IsActionSuccessful = false,
                        ErrorMessage = "You are not allowed to attach back to the original company because it already does not exist."
                    };
                }
    
                string[] userRoles = await GetRolesOfUserAsync(selectedUser.Id);
    
                var targetCompany = await _companyInfoService.RetrieveCompanyAsync(selectedUser.BeforeSpyingOriginalCompanyId.Value);
    
                if (targetCompany == null)
                {
                    return new ServiceSingleRecordInsertOrUpdateResponse
                    {
                        IsActionSuccessful = false,
                        ErrorMessage = "You are not allowed to attach back to the original company because it already does not exist."
                    };
                }
    
                if (userRoles.Contains(Roles.SuperUser) && selectedUser.CompanyId == currentCompanyId && selectedUser.BeforeSpyingOriginalCompanyId != null)
                {
                    selectedUser.CompanyId = selectedUser.BeforeSpyingOriginalCompanyId.Value;
                    selectedUser.BeforeSpyingOriginalCompanyId = null;
    
                    await _dbIdentity.SaveChangesAsync();
    
                    return new ServiceSingleRecordInsertOrUpdateResponse { RecordCode = currentCompanyName, IsActionSuccessful = true, ErrorMessage = null };
                }
    
                return new ServiceSingleRecordInsertOrUpdateResponse
                {
                    IsActionSuccessful = false,
                    ErrorMessage = "You are not allowed to detach from this company because you are not Super User or you do not belong to your current company. Please retry."
                };
            }
    
    
    
    
            private async Task<UserInfo> GetUserInfoAsync(ApplicationUser user)
            {
                if (user == null)
                {
                    return new UserInfo();
                }
    
                var userCompany = await GetCompanyInfoOfUserAsync(user.CompanyId);
    
                bool isSuperUserAttachingToUserCompany = user.BeforeSpyingOriginalCompanyId != null;
    
                return new UserInfo()
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    FullName = user.FullName,
                    Email = user.Email,
                    PhoneNumber = user.PhoneNumber,
                    CompanyId = user.CompanyId,
                    CompanyName = userCompany.CompanyName,
                    CompanyBrandAbbreviation = userCompany.BrandAbbreviation,
                    CompanyTypeId = userCompany.CompanyType,
                    CompanyType = userCompany.CompanyTypeName,
                    Roles = await GetRolesOfUserAsync(user.Id),
                    EmailConfirmed = user.EmailConfirmed,
                    Status = user.Status,
                    CompanyVerified = isSuperUserAttachingToUserCompany || userCompany.IsVerified,
                    CompanyStatus = isSuperUserAttachingToUserCompany || userCompany.Status,
                    BeforeSpyingOriginalCompanyId = user.BeforeSpyingOriginalCompanyId,
                    IsResetPasswordUponLoginNeeded = user.IsResetPasswordUponLoginNeeded,
                    IsSubscribeWhatsAppMessage = user.IsSubscribeWhatsAppMessage,
                    CreatedAt = user.CreatedAt,
                    HasPortnetCredentials = userCompany.PortnetUserName != null && userCompany.PortnetUserPassword != null,
                  
                };
            }
    
            private async Task<UserInfo> GetUserInfoWithoutCompanyInfoAsync(ApplicationUser user)
            {
                if (user == null)
                {
                    return new UserInfo();
                }
    
                return new UserInfo()
                {
                    Id = user.Id,
                    FullName = user.FullName,
                    Email = user.Email,
                    PhoneNumber = user.PhoneNumber,
                    CompanyId = user.CompanyId,
                    Roles = await GetRolesOfUserAsync(user.Id),
                    Status = user.Status,
                    EmailConfirmed = user.EmailConfirmed,
                    BeforeSpyingOriginalCompanyId = user.BeforeSpyingOriginalCompanyId,
                    IsResetPasswordUponLoginNeeded = user.IsResetPasswordUponLoginNeeded,
                    CreatedAt = user.CreatedAt
                };
            }
    
            private async Task<CompanyProfileManageViewModel> GetCompanyInfoOfUserAsync(long userCompanyId)
            {
                if (userCompanyId == 0)
                {
                    return new CompanyProfileManageViewModel();
                }
    
                return await _companyInfoService.RetrieveCompanyAsync(userCompanyId);
            }
    
            private async Task<string[]> GetRolesOfUserAsync(string userId)
            {
                return await _dbIdentity.UserClaims
                        .Where(uc => uc.UserId == userId && uc.ClaimType == Constants.RoleClaimTypeName)
                        .Select(x => x.ClaimValue)
                        .ToArrayAsync();
            }
    
            public async Task<ServiceSingleRecordInsertOrUpdateResponse> UpdateUserAsync(CompanyUserManageViewModel model, string actionUser)
            {
                var selectedUser = await _dbIdentity.Users.FirstOrDefaultAsync(u => u.Id == model.UserId);
    
                if (selectedUser == null)
                {
                    return new ServiceSingleRecordInsertOrUpdateResponse { IsActionSuccessful = false, ErrorMessage = "No such user exists." };
                }
    
                selectedUser.FullName = model.Name;
                selectedUser.PhoneNumber = model.Phone;
                selectedUser.Status = model.Status;
                selectedUser.IsSubscribeWhatsAppMessage = model.IsSubscribeWhatsAppMessage;
    
                bool isCurrentUserHaulio = (await _companyInfoService.GetHaulioCompanyIdsAsync()).Contains(selectedUser.CompanyId);
    
                var correspondingSuperUserRole = await _dbIdentity.UserClaims.FirstOrDefaultAsync(uc => uc.UserId == model.UserId && uc.ClaimType == Constants.RoleClaimTypeName && uc.ClaimValue == Roles.SuperUser);
                var correspondingCompanyAdminRole = await _dbIdentity.UserClaims.FirstOrDefaultAsync(uc => uc.UserId == model.UserId && uc.ClaimType == Constants.RoleClaimTypeName && uc.ClaimValue == Roles.CompanyAdmin);
                var correspondingNormalUserRole = await _dbIdentity.UserClaims.FirstOrDefaultAsync(uc => uc.UserId == model.UserId && uc.ClaimType == Constants.RoleClaimTypeName && uc.ClaimValue == Roles.CompanyNormalUser);
    
                bool isUserNowSuperUser = correspondingSuperUserRole != null;
                bool isUserNowCompanyAdmin = correspondingCompanyAdminRole != null;
    
                if (model.IsAdmin)
                {
                    if (!isUserNowSuperUser && isCurrentUserHaulio)
                    {
                        await _dbIdentity.UserClaims.AddAsync(new IdentityUserClaim<string>
                        {
                            ClaimType = Constants.RoleClaimTypeName,
                            ClaimValue = Roles.SuperUser,
                            UserId = model.UserId
                        });
    
                        if (correspondingNormalUserRole != null)
                        {
                            _dbIdentity.Remove(correspondingNormalUserRole);
                        }
                    }
                    else if (!isUserNowCompanyAdmin && !isCurrentUserHaulio)
                    {
                        await _dbIdentity.UserClaims.AddAsync(new IdentityUserClaim<string>
                        {
                            ClaimType = Constants.RoleClaimTypeName,
                            ClaimValue = Roles.CompanyAdmin,
                            UserId = model.UserId
                        });
    
                        if (correspondingNormalUserRole != null)
                        {
                            _dbIdentity.Remove(correspondingNormalUserRole);
                        }
                    }
    
                }
                else if (!model.IsAdmin)
                {
                    if (isUserNowSuperUser)
                    {
                        _dbIdentity.Remove(correspondingSuperUserRole);
                    }
    
                    if (isUserNowCompanyAdmin)
                    {
                        _dbIdentity.Remove(correspondingCompanyAdminRole);
                    }
    
                }
    
                await _dbIdentity.SaveChangesAsync();
    
                int numberOfRolesCurrentUserHas = await _dbIdentity.UserClaims.CountAsync(uc => uc.UserId == model.UserId && uc.ClaimType == Constants.RoleClaimTypeName);
    
                // Make sure the user has at least the lowest role
                if (numberOfRolesCurrentUserHas == 0)
                {
                    await _dbIdentity.UserClaims.AddAsync(new IdentityUserClaim<string>
                    {
                        ClaimType = Constants.RoleClaimTypeName,
                        ClaimValue = Roles.CompanyNormalUser,
                        UserId = model.UserId
                    });
    
                    await _dbIdentity.SaveChangesAsync();
                }
    
                return new ServiceSingleRecordInsertOrUpdateResponse { IsActionSuccessful = true, RecordCode = selectedUser.Id };
            }
    
            /// <summary>
            /// For driver app.
            /// </summary>
            /// <param name="userId"></param>
            /// <param name="phoneNumber"></param>
            /// <returns></returns>
            public async Task<ServiceStatusResponse> UpdateUserPhoneNumberAndUserNameAsync(string userId, string phoneNumber)
            {
                var selectedUser = await _dbIdentity.Users.FirstOrDefaultAsync(u => u.Status && u.Id == userId);
    
                if (selectedUser == null)
                {
                    return new ServiceStatusResponse { IsActionSuccessful = false, Message = "No such user exists." };
                }
    
                selectedUser.PhoneNumber = phoneNumber;
                selectedUser.UserName = phoneNumber;
                selectedUser.NormalizedUserName = phoneNumber;
    
                await _dbIdentity.SaveChangesAsync();
    
                return new ServiceStatusResponse { IsActionSuccessful = true, Message = "User phone number is updated successfully." };
            }
    
            public Task<UserInfo> UpdateLogoutTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }
    
            Task<UserInfo> IUserInfoService.UpdateLoginTimeAsync(string userId)
            {
                throw new NotImplementedException();
            }
        }
    }

    using Community.Data.CommonDataTypes;
    using Community.Data.Entities.Companies.ViewModels;
    using Community.Data.Entities.Users;
    using Community.Data.Entities.Users.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Community.Service.Users
    {
        public interface IUserInfoService
        {
            CompanyRoleViewModel GetCompanyRole();
    
            Task<IEnumerable<CompanyRoleViewModel>> GetAllCompanyRolesAsync(long companyID);
    
            Task<CompanyRoleViewModel> GetCompanyRoleAsync(string companyRoleId);
    
            Task<ServiceSingleRecordInsertOrUpdateResponse> CreateCompanyRoleAsync(CompanyRoleViewModel model, long companyId);
    
            Task<ServiceSingleRecordInsertOrUpdateResponse> UpdateCompanyRoleAsync(CompanyRoleViewModel model);
    
            Task ApproveUserAccountsOfCompanyAsync(long companyId);
    
            Task<ServiceStatusResponse> DeleteUserAsync(string userId);
    
            Task<int> RetrieveNumberOfUsersAsync();
    
            Task<IEnumerable<UserInfo>> RetrieveAllUsersAsync(bool includingInactive = false);
    
            Task<string> GenerateCsvContentForAllUsersAsync(bool includingInactive = false);
    
            Task<UserInfo> RetrieveUserInfoAsync(string userId);
    
            Task<UserInfo> RetrieveUserInfoWithoutCompanyByPhoneNumberAsync(string phoneNumber);
    
            Task<UserInfo> RetrieveUserInfoByEmailAsync(string userEmail);
    
            Task<ServiceStatusResponse<UserInfo>> RetrieveUserInfoByPhoneNumberAsync(string phoneNumber);
    
            Task<string> RetrieveUserFullNameByEmailAsync(string userEmail);
    
            Task<CompanyProfileManageViewModel> RetrieveUserCompanyInfoByEmailAsync(string userEmail);
    
            Task<long> RetrieveCompanyIdByEmailAsync(string userEmail);
    
            Task<IEnumerable<UserInfo>> RetrieveInfoOfAllUsersInCompanyAsync(long companyId);
    
            Task<List<UserIdEmailViewModel>> RetrieveIdEmailOfAllUsersInCompanyAsync(long companyId);
    
            Task<List<UserIdEmailFullNameViewModel>> RetrieveIdEmailFullNameOfAllUsersAsync(bool includingInactive = false);
    
            Task<string[]> RetrieveEmailsOfAllUsersInCompanyAsync(long companyId);
    
            Task<IEnumerable<UserInfo>> RetrieveInfoOfAllSuperUsersAsync();
    
            Task<bool> SubmitNewUserAccountCreationRequest(NewUserAccountCreationRequestViewModel model, string createdBy);
    
            Task<NewUserAccountCreationRequest> RetrieveNewUserAccountCreationRequestAsync(string userEmail);
    
            Task<ServiceSingleRecordInsertOrUpdateResponse> UpdateUserAsync(CompanyUserManageViewModel model, string actionUser);
    
            Task<ServiceStatusResponse> UpdateUserPhoneNumberAndUserNameAsync(string userId, string phoneNumber);
    
            Task<bool> SetUserAccountCreationRequestAsDoneAsync(string userEmail);
    
            Task<ServiceSingleRecordInsertOrUpdateResponse> AttachUserToAnotherCompany(string currentUserId, long currentCompanyId, long targetCompanyId);
    
            Task<ServiceSingleRecordInsertOrUpdateResponse> DetachUserFromCompanyBackToOriginalCompany(string currentUserId, long currentCompanyId, string currentCompanyName);
    
            Task<UserInfo> UpdateLoginTimeAsync(string userId);
    
            Task<UserInfo> UpdateLogoutTimeAsync(string userId);
        }
    }
    using Community.Constant.Extensions;
    using Community.Data.CommonDataTypes;
    using Community.Data.Entities.Companies;
    using Microsoft.AspNetCore.Identity;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Text;
    
    namespace Community.Data.Entities.Users
    {
        // Add profile data for application users by adding properties to the ApplicationUser class
        public class ApplicationUser : IdentityUser
        {
            public string FullName { get; set; }
    
            public long CompanyId { get; set; }
    
            public long? BeforeSpyingOriginalCompanyId { get; set; }
    
            public bool IsResetPasswordUponLoginNeeded { get; set; }
    
            public bool IsWelcomingFromTraditionalWebsiteNeeded { get; set; }
    
            public bool Status { get; set; } = true;
    
            public bool IsSubscribeWhatsAppMessage { get; set; } = true;
    
            public DateTime CreatedAt { get; set; } = DateTime.Now;
    
            [MaxLength(50)]
            public string VerificationCode { get; set; }
    
            public DateTime VerificationCodeExpiryDate { get; set; } = DateTime.Today.ToSqlDefaultDateTime();
    
            public DateTime LoginTime { get; set; } 
            public DateTime LogoutTime { get; set; }
    
    
        }
    }
    I put my <g class="gr_ gr_24 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" data-gr-id="24" id="24">break point</g> (below) will get the default <g class="gr_ gr_71 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="71" id="71">date time</g> that <g class="gr_ gr_78 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" data-gr-id="78" id="78">mention</g> in the <g class="gr_ gr_119 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="119" id="119">theread</g>
    public DateTime LoginTime { get; set; } 
    public DateTime LogoutTime { get; set; }
    
    




    I am <g class="gr_ gr_5 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="5" id="5">newbie</g> in <g class="gr_ gr_6 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="6" id="6">enterprise</g> as <g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="7" id="7">developer</g>.



    Tuesday, January 22, 2019 3:02 AM
  • That's a lot of code...

    Can you remove the html tags from your post, please? It's hard to read :/.

    Have you set a breakpoint right behind where you set the login time? Is it ok at this point? Are the other properties ok, too?

    Wednesday, January 23, 2019 6:02 PM
  • Hi ,

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer , so that it will help other members to find solution quickly if they faces similar issue.

    Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, January 29, 2019 8:45 AM
    Moderator
  • ASP.NET Identity database and coding can be discussed at the ASP.NET forums.

    https://forums.asp.net/

    Tuesday, January 29, 2019 3:19 PM