Code:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Services;
using SharedClasses.DTO.TokenDTOs;
using SharedClasses.DTO;
using SharedClasses.Handlers;
using Services.Interfaces;
using MainProgram.BL;
using Repositories.Interfaces;
using System.Net;
namespace MainProgram.Controllers;
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly PerformanceHandler ph = new PerformanceHandler();
private readonly responseHandler rh;
private readonly ErrorHandler er = new ErrorHandler();
//private readonly IsharedVariablesService variablesService;
private readonly IEnterProgLogService progLogService;
private readonly IUserService usersService;
private readonly ItblUserPermsService userPermissionService;
private readonly IUserDepartmentService userDepService;
public UsersController(
/*IsharedVariablesService sharedVariableService,*/
IEnterProgLogService enterProgLogService,
IUserService userService,
ItblUserPermsService userPermsService,
IBranchesService branchService,
IDepartmentsService departmentService, IUserDepartmentService userDepService)
{
//this.variablesService = sharedVariableService;
this.progLogService = enterProgLogService;
this.usersService = userService;
this.userPermissionService = userPermsService;
this.userDepService = userDepService;
this.rh = new responseHandler(
null,
branchService,
userService,
userPermsService,
departmentService,
enterProgLogService,
null,null,null, userDepService
/*sharedVariableService*/);
}
private TokenValidation tokenInvalid()
{
TokenValidation token = new TokenValidation();
token.IsToken = false;
this.HttpContext.Response.StatusCode = StatusCodeHandler.unAuthorized();
return token;
}
[HttpPost("deleteUserDepartment")]
public IActionResult deleteUserDepartment(TokenUserDepParam data)
{
string msg = "";
IActionResult response;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
var isAdminResponse = usersService.isAdminUser(progLogService.userID);//Check if user requested to do the function is admin or not.
if (isAdminResponse.IsAdmin)
{
var result = userDepService.deleteUserDepartment(data.UserDep.UserId,data.UserDep.DepartmentId);
if (result)
response = Ok(rh.createResponse(StatusCodeHandler.statusCode(), MessageHandler.DataDeleted(), result));
else response = BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), MessageHandler.DeleteFail(), result));
}//If
else response = Forbid(rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}//If
else
{
var res = tokenInvalid();
response = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}//Else
ph.FunctionFinish();
ph.PerformanceToLog("addOrUpdateUserDepartment");
return response;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "addOrUpdateUserDepartment", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
[HttpPost("addOrUpdateUserDepartment")]
public IActionResult addOrUpdateUserDepartment(TokenUserDepBoolParam data)
{
string msg = "";
IActionResult response;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
var isAdminResponse = usersService.isAdminUser(progLogService.userID);//Check if user requested to do the function is admin or not.
if (isAdminResponse.IsAdmin)
{
var result = userDepService.addOrUpdateUserDepartment(data.UserDep, ref msg, data.isAdd);
if (result)
response = Ok(rh.createResponse(StatusCodeHandler.statusCode(), msg, result));
else response = BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), msg, result));
}//If
else response = Forbid(rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}//If
else
{
var res = tokenInvalid();
response = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}//Else
ph.FunctionFinish();
ph.PerformanceToLog("addOrUpdateUserDepartment");
return response;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "addOrUpdateUserDepartment", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
[HttpPost("getUserDepartments")]
public IActionResult getUserDepartments(TokenIndxParam data)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), "", userDepService.getUserDepartments(data.indx)));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("getUserDepartments");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getUserDepartments", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
[HttpPost("updateUserSignature")]
public IActionResult updateUserSignature(TokenIndxStringParam data)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
var response = usersService.updateUserSignature(data.Indx, data.Name);
if (response)
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), MessageHandler.SignatureUpdated(), response));
else result = BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), MessageHandler.ErrSignatureUpdate(), response));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("updateUserSignature");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "updateUserSignature", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
[HttpPost("getUserSignature")]
public IActionResult getUserSignature(TokenIndxParam data)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), "", usersService.getUserSignature(data.indx)));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("getUserSignature");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getUserSignature", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
[HttpPost("getUserSettings")]
public IActionResult getUserSettings(Token token)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(token.token))
{
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), "", usersService.getUserTblSetting(progLogService.userID)));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("getUserSettings");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getUserSettings", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
[HttpPost("isAdminUser")]
public IActionResult isAdmin(Token token)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(token.token))
{
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), "", usersService.isAdminUser(progLogService.userID)));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("isAdminUser");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "isAdminUser", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function to kick an online user
/// </summary>
/// <param name="data">Data contains the requisting user token and the user token desired to be kicked from the app.</param>
/// <returns>boolean if the function succeded</returns>
[HttpPost("kickUser")]
public IActionResult kickUser([FromBody]TokenIndxParam data)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), "", progLogService.kickUser(data.indx)));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("kickUser");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "kickUser", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function that gets all the data needed for the data entry home page.
/// </summary>
/// <param name="token">User logged in token.</param>
/// <returns>Response that contains all users and branches from the database, a message and the http request Code.</returns>
[HttpPost("getUsersforDataEntry")]
public IActionResult getUsersForDataEntry([FromBody]Token token)
//gets users for data entry page along with the branches
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(token.token))
{
if (usersService.isAdminUser(progLogService.userID).IsAdmin)
if(usersService.canEnterUsers(progLogService.userID))
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), MessageHandler.DataRetrieved(), rh.createUsersBranchesResponse()));
else result = Problem(
statusCode: 403,
detail: rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.CannotEnterUsers(), null));
else result = Problem(
statusCode: 403,
detail: rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}
else
{
var tokenCheck = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), tokenCheck));
}
ph.FunctionFinish();
ph.PerformanceToLog("getUsersForDataEntry");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getUsersForDataEntry", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function to delete a certain user by sending its indx.
/// </summary>
/// <param name="token">User logged in token.</param>
/// <param name="indx">User indx that is desired to remove.</param>
/// <returns>Response contains a boolean value, a message and the http request Code.</returns>
[HttpPost("deleteUser")]
public IActionResult deleteUser([FromBody] TokenIndxParam data)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
if (usersService.isAdminUser(progLogService.userID).IsAdmin)
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), MessageHandler.DataDeleted(), usersService.deleteUserByIndx(data.indx)));
else result = Forbid(rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("deleteUser");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "deleteUser", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function to get all the data needed in the add user page.
/// </summary>
/// <param name="token">User logged in token.</param>
/// <returns>Languages,Branches,Categories and user types.</returns>
[HttpPost("getDataForAddUser")]
public IActionResult getDataForAddUser([FromBody] Token token)
//gets the data for the add user page..
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(token.token))
{
if (usersService.isAdminUser(progLogService.userID).IsAdmin)
result = Ok(rh.createResponse(StatusCodeHandler.statusCode(), MessageHandler.DataRetrieved(), rh.createAddUserResponse()));
else result = Forbid(rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("getDataForAddUser");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getDataForAddUser", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function to get the data needed for the edit user page.
/// </summary>
/// <param name="token">User logged in token.</param>
/// <param name="indx">User indx to get its data.</param>
/// <returns>User details,Languages,Branches,Categories,User Types ,User settings , Departments and user permissions.</returns>
[HttpPost("getDataForEditUser")]
public IActionResult getDataEditUser([FromBody] TokenIndxParam data)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(data.token.token))
{
if (usersService.isAdminUser(progLogService.userID).IsAdmin)
result = Ok(
rh.createResponse(
StatusCodeHandler.statusCode(),
MessageHandler.DataRetrieved(),
rh.createEditUserResponse(data.indx)));
else result = Forbid(rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}
else
{
var res = tokenInvalid();
result = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}
ph.FunctionFinish();
ph.PerformanceToLog("getDataForEditUser");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getDataForEditUser", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function to get all the online users that exists in the app now.
/// </summary>
/// <param name="token">User logged in token</param>
/// <returns>a list of online users.</returns>
[HttpPost("getOnlineUsers")]
public IActionResult getOnlineUsers([FromBody] Token token)
{
IActionResult result;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(token.token))
{
result = Ok(
rh.createResponse(
StatusCodeHandler.statusCode(),
MessageHandler.DataRetrieved(),
usersService.getOnlineUsers()));
}
else
{
var res = tokenInvalid();
result = Unauthorized(
rh.createResponse(
StatusCodeHandler.unAuthorized(),
MessageHandler.InvalidToken(),
res));
}
ph.FunctionFinish();
ph.PerformanceToLog("getOnlineUsers");
return result;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "getOnlineUsers", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
/// <summary>
/// Function to add or update a user in the database.
/// </summary>
/// <param name="token">User logged in token</param>
/// <param name="userDetails">User details that you wanna update</param>
/// <returns>A response contains the http request code, the data you need and the message</returns>
[HttpPost("addOrUpdateUser")]
public IActionResult addOrUpdateUser([FromBody] AddOrUpdateUserVariable userDetails)
{
string msg = "";
IActionResult response;
try
{
ph.FunctionBegin();
if (progLogService.validateToken(userDetails.token.token))
{
var isAdminResponse = usersService.isAdminUser(progLogService.userID);//Check if user requested to do the function is admin or not.
if (isAdminResponse.IsAdmin)
{
if (userDetails.userToAdd.Indx != null && userDetails.userToAdd.Indx > 0)
{
var result = usersService.updateUser(userDetails.userToAdd, ref msg);//Updates user details
if (!result)
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), msg, null));
var permsResult = userPermissionService.updateUserPermissionsList(userDetails.permissionsToAdd);//Updates user permissions.
response = Ok(rh.createResponse(StatusCodeHandler.statusCode(), msg, result && permsResult));
}//If
else
{
var insertResponse = usersService.insertUser(userDetails.userToAdd, ref msg);
if (insertResponse == null)
{
response = BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), msg, insertResponse));
}//If
else
{
response = Ok(rh.createResponse(StatusCodeHandler.statusCode(), msg, insertResponse));
}//Else
}//Else
}//If
else response = Forbid(rh.createResponse(StatusCodeHandler.forbidden(), MessageHandler.NotAdmin(), null));
}//If
else
{
var res = tokenInvalid();
response = Unauthorized(rh.createResponse(StatusCodeHandler.unAuthorized(), MessageHandler.InvalidToken(), res));
}//Else
ph.FunctionFinish();
ph.PerformanceToLog("addOrUpdateUser");
return response;
}
catch (Exception ex)
{
er.writeToErrorLog(MessageHandler.ProjectName(), MessageHandler.DataEntry(), "addOrUpdateUser", ex);
return BadRequest(rh.createResponse(StatusCodeHandler.badRequest(), ex.Message, null));
}
}
}
Main Repository Functionality:
Code:
using EFDal.Models;
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Tokens;
using Microsoft.EntityFrameworkCore;
using SharedClasses;
using Repositories.Interfaces;
using SharedClasses.Handlers;
using SharedClasses.Selectors;
using SharedClasses.DTO;
using Repositories.MainRepositories;
using EFDal.Views;
using System.Net.Sockets;
namespace Repositories;
public class UsersRepository : MDbRepository<User,MDbContext> , IUsersRepository
{
private MDbContext db;
private List<IndxName> Departments;
public UsersRepository(MDbContext db) : base(db)
{
this.db = db;
}
public List<IndxName> getClerks(bool isBlocked,int companyID, int branchID)
{
try
{
var mainBranchVar = db.WebVariables.Where(v => v.Company == companyID && v.Branch == branchID && v.WebSiteCode.ToUpper() == "tco".ToUpper()).FirstOrDefault();
var isInMainBranch = (SharedClasses.SharedFunctions.ifNullOrEmpty(mainBranchVar == null ? "N" : mainBranchVar.VariableValue ,"N").ToUpper() == "Y".ToUpper());
var branchIndxes = db.Branches.Where(b => b.Company == companyID && !isInMainBranch ? b.Indx == branchID : true).Select(c => c.Indx).ToList();
var clerks = (from users in db.Users
where branchIndxes.Contains((int)users.Branch)
where isBlocked ? users.EnterTheProgram == true : true
orderby users.UserName
select new IndxName
{
Name = users.UserName,
Indx = users.Indx
}).ToList<IndxName>();
return clerks;
}
catch
{
throw;
}
}
public UserSettingsSelector? getUserSettings(int indx)
{
UserSettingsSelector? dataToReturn = new UserSettingsSelector();
try
{
dataToReturn = db.Users.Where(u => u.Indx == indx).Select(u => new UserSettingsSelector
{
EnterTheProgram = u.EnterTheProgram,
EnterData = u.EnterData,
EnterUsers = u.EnterUsers,
EnterReservations = u.EnterReservations,
Enterallotment = u.Enterallotment,
EnterDohot = u.EnterDohot,
EnterQueries = u.EnterQueries,
CanConfirm = u.CanConfirm,
EnterAccounting = u.EnterAccounting,
EnterPriceListForHotel = u.EnterPriceListForHotel,
EnterNazarenePackages = u.EnterNazarenePackages,
EnterBusManagment = u.EnterBusManagment,
EnterFlights = u.EnterFlights,
EnterCountries = u.EnterCountries,
EnterRoomType = u.EnterRoomType,
EnterBusPrices = u.EnterBusPrices,
ChangeConstants = u.ChangeConstants,
EnterHotelNotes = u.EnterHotelNotes,
EnterServicePrices = u.EnterServicePrices,
EnterAgents = u.EnterAgents,
EnterPromotions = u.EnterPromotions,
EnterMaxDiscount = u.EnterMaxDiscount,
EnterShuttlePrices = u.EnterShuttlePrices,
EnterVisaPrices = u.EnterVisaPrices,
CanCheckServices = u.CanCheckServices,
CanSeeNetPrice = u.CanSeeNetPrice,
MakeConfCode = u.MakeConfCode,
EnterIncoming = u.EnterIncoming,
CanAllowResvs = u.CanAllowResvs,
CanSeeSremarks = u.CanSeeSremarks,
CanGiveResvCode = u.CanGiveResvCode,
CanGiveVchcode = u.CanGiveVchcode,
CanControlResvs = u.CanControlResvs,
CanGiveOpenCode = u.CanGiveOpenCode,
CanGiveDisCode = u.CanGiveDisCode,
CanChangeVchfromVchscreen = u.CanChangeVCHfromVCHscreen
}).FirstOrDefault();
return dataToReturn;
}
catch (Exception ex)
{
throw;
}
}
public IEnumerable<User> getAll(bool? isActive = null)
{
try
{
if (isActive != null && isActive == true)
return db.Users.Where(u => u.EnterTheProgram == true).ToList().OrderBy(u => u.UserName);
else if (isActive != null && isActive == false)
return db.Users.Where(u => u.EnterTheProgram == false).ToList().OrderBy(u => u.UserName);
return db.Users.ToList().OrderBy(u => u.UserName);
}
catch (Exception ex)
{
throw;
}
}
public IEnumerable<IndxName> getAllFreeLancers()
{
try
{
List<IndxName> users = db.Users
.Where(user => user.IsFreeLancer == true)
.Select(user => new IndxName
{
Name = user.UserName,
Indx = user.Indx
})
.OrderBy(user => user.Name).ToList();
if (users.Count > 0)
return users;
else throw new Exception("There are no free lancer users.");
}
catch (Exception ex)
{
throw;
}
}
public IEnumerable<AdvancedUser> getAdvancedUsers(int branchIndx, int userIndx, string? userName, bool? isBlocked = false)
//Previous Name: ShowUsers
//function that gets 4 parameters isblocked branchIndx userIndx and username
//returns a list of user with 3 columns added at the end of the table (BranchName , LanguageName ,UserTypeName)
{
try
{
List<AdvancedUser> users = (from User in db.Users
join branch in db.Branches on User.Branch equals branch.Indx into newBTable
from subBranch in newBTable.DefaultIfEmpty() // does the left join to the branches table
join languages in db.Languages on User.Lang equals languages.Indx into newLTable
from subLanguages in newLTable.DefaultIfEmpty() // does the left join to the languages table
join docketType in db.DocketTypes on User.UserType equals docketType.Indx
where (branchIndx != null && branchIndx > 0 ? User.Branch == branchIndx : true) &&
(userIndx != null && userIndx > 0 ? User.Indx == userIndx : true) &&
(!(bool)isBlocked ? User.EnterTheProgram == true : true) &&
(userName != null ? User.UserName == userName : true)
orderby User.Branch ascending, User.UserName ascending // order the data by the branch index first then by the user name
select new AdvancedUser
{
Indx = User.Indx,
UserName = User.UserName,
Password = User.Password,
EnterTheProgram = User.EnterTheProgram,
EnterData = User.EnterData,
EnterUsers = User.EnterUsers,
EnterReservations = User.EnterReservations,
Enterallotment = User.Enterallotment,
EnterDohot = User.EnterDohot,
EnterQueries = User.EnterQueries,
CanConfirm = User.CanConfirm,
EnterAccounting = User.EnterAccounting,
EnterPriceListForHotel = User.EnterPriceListForHotel,
EnterNazarenePackages = User.EnterNazarenePackages,
EnterBusManagment = User.EnterBusManagment,
EnterFlights = User.EnterFlights,
EnterCountries = User.EnterCountries,
EnterRoomType = User.EnterRoomType,
EnterBusPrices = User.EnterBusPrices,
ChangeConstants = User.ChangeConstants,
EnterHotelNotes = User.EnterHotelNotes,
EnterServicePrices = User.EnterServicePrices,
EnterAgents = User.EnterAgents,
EnterMaxDiscount = User.EnterMaxDiscount,
EnterShuttlePrices = User.EnterShuttlePrices,
EnterVisaPrices = User.EnterVisaPrices,
EnterIncoming = User.EnterIncoming,
EnterPromotions = User.EnterPromotions,
CanCheckServices = User.CanCheckServices,
CanSeeNetPrice = User.CanSeeNetPrice,
MakeConfCode = User.MakeConfCode,
CanAllowResvs = User.CanAllowResvs,
CanSeeSremarks = User.CanSeeSremarks,
CanGiveResvCode = User.CanGiveResvCode,
CanGiveVchcode = User.CanGiveVchcode,
CanControlResvs = User.CanControlResvs,
CanGiveOpenCode = User.CanGiveOpenCode,
CanGiveDisCode = User.CanGiveDisCode,
UserCatagory = User.UserCatagory,
ConfCode = User.ConfCode,
Branch = User.Branch,
Lang = User.Lang,
UserType = User.UserType,
UserCategory2 = User.UserCategory2,
OpenDate = User.OpenDate,
Email = User.Email,
DomainLogin = User.DomainLogin,
FinAccIndx = User.FinAccIndx,
AccIndx = User.AccIndx,
Phone = User.Phone,
Mobile = User.Mobile,
Skype = User.Skype,
IsFreeLancer = User.IsFreeLancer,
CanChangeVchfromVchscreen = User.CanChangeVCHfromVCHscreen,
BranchName = subBranch.Branch1,
LanguageName = subLanguages.Lang,
UserTypeName = docketType.DocketType1
}).ToList();
if (users.Count > 0)
return users;
else throw new Exception("There are no such users.");
}
catch (Exception ex)
{
throw;
}
}
public bool updateUserSignature(int indx, string signature)
{
try
{
var user = db.Users.Where(u=>u.Indx == indx).FirstOrDefault();
if (user != null)
{
user.Signature = signature;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return true;
}
else return false;
}
catch
{
throw;
}
}
public string getUserSignature(int indx)
{
try
{
return db.Users.Where(u => u.Indx == indx).Select(u => u.Signature).FirstOrDefault();
}
catch
{
throw;
}
}
private static string getDepartmentName(List<IndxName> Departments , int indx)
{
try
{
return Departments.Where(d=>d.Indx == indx).Select(d=>d.Name).FirstOrDefault();
}
catch
{
throw;
}
}
public IEnumerable<UsersForDataEntry> getForDataEntry()
//Previous name: ShowUsersForDataEntry
// Function that returns the data of users for the data entry
{
try
{
this.Departments = db.Departments.Select(d=> new IndxName { Indx = d.Indx , Name = d.DepartmentName }).ToList();
var userDepartments = db.UserDepartments.GroupBy(dv => dv.UserId)
.ToDictionary(group => group.Key,
group => group.Where(g => g.IsMain == true).FirstOrDefault() ?? group.FirstOrDefault());
var qryJoin = (from User in db.Users
join branch in db.Branches on User.Branch equals branch.Indx into newBTable
from subBranch in newBTable.DefaultIfEmpty() // does the left join to the branches table
//join departments in db.UserDepartments on User.Indx equals departments.UserId
join departments2 in db.UserDepartments on User.Indx equals departments2.UserId into newDepartments2
//join department in db.Departments on subDepartments.DepartmentId equals department.Indx// into newDTable
//from subDepartment in newDTable.DefaultIfEmpty() // does the left join to the departments table
orderby subBranch.Indx, User.UserName ascending // order the data by the branch index first then by the user name
select new UsersForDataEntry
{
Indx = User.Indx,
UserName = User.UserName,
Password = User.Password,
UserCatagory = User.UserCatagory,
Email = User.Email,
EnterTheProgram = User.EnterTheProgram,
BranchName = subBranch.Branch1, // name of the new column in the new table of data
DepartmentName = newDepartments2.ToList().Count() > 0 ? getDepartmentName(this.Departments, userDepartments[User.Indx].DepartmentId) : "", // name of the new column in the new table of data
Signature = User.Signature
}).ToList();
if (qryJoin.Count > 0)
return qryJoin;
else throw new Exception("There are no users in the database.");
}
catch (Exception ex)
{
throw;
}
}
public IEnumerable<User> getByBranchId(int branchIndx, bool? isActive = null)
{
try
{
if (isActive != null && isActive == true)
return db.Users.Where(u => u.Branch == branchIndx && u.EnterTheProgram == true).ToList();
else if (isActive != null && isActive == false)
return db.Users.Where(u => u.Branch == branchIndx && u.EnterTheProgram == false).ToList();
return db.Users.Where(u => u.Branch == branchIndx).ToList();
}
catch (Exception ex)
{
throw;
}
}
public User getBy(int? indx, string? username = null)
{
try
{
if (indx.HasValue)
return db.Users.Where(u => u.Indx == indx).FirstOrDefault();
else if (!username.IsNullOrEmpty())
return db.Users.Where(u => u.UserName == username).FirstOrDefault();
return null;
}
catch (Exception ex)
{
throw;
}
}
public List<OnlineUsersSelector> getOnlineUsers()
{
try
{
var onlineUsersQuery = (from userEnterProLog in db.UserEnterProgLogs
join users in db.Users on userEnterProLog.UserId equals users.Indx into newEnterProgLog
where DateTime.Now < userEnterProLog.ValidTime
where userEnterProLog.ExitTime == null
from newUsers in newEnterProgLog.DefaultIfEmpty()
orderby userEnterProLog.UserId descending, userEnterProLog.CurrentTime descending
select new OnlineUsersSelector
{
Indx = newUsers.Indx,
UserName = newUsers.UserName,
Email = newUsers.Email,
LatestAction = userEnterProLog.CurrentTime,
ValidTime = userEnterProLog.ValidTime
}).ToList();
return onlineUsersQuery;
}
catch (Exception ex)
{
throw;
}
}
public SharedClasses.Selectors.IndxName insert(User user)
{
try
{
var entity = db.Users.Add(user).Entity;
db.SaveChanges();
SharedClasses.Selectors.IndxName dataToReturn = new SharedClasses.Selectors.IndxName
{
Indx = entity.Indx,
Name = entity.UserName
};
return dataToReturn;
}
catch (Exception ex)
{
throw;
}
}
public List<User> getAdminUsers()
{
try
{
return db.Users.Where(u=>u.UserCategory2 == "Resv Manager").ToList();
}
catch
{
throw;
}
}
public List<User> getEmails(string email, int indx)
{
try
{
return db.Users.Where(u => u.Email == email && u.Indx != indx).ToList();
}
catch
{
throw;
}
}
}
Is all proof of work your own work?