Create MVC project
Web.config
connectionStrings>
add name="RDX_FBA_TRACKING" connectionString="Data Source=serverIP;Initial Catalog=dbName; user Id=USer; password=Pass; Integrated Security =False;" providerName="System.Data.SqlClient" />
/connectionStrings>
AccountController
using RDX.Domain.DTO;
using RDX.Domain.Entities;
using RDX.Infrastructure.Helper;
using RDX.Infrastructure.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RDX.FBATracking.Controllers
{
public class AccountController : Controller
{
public ActionResult Login(string returnUrl)
{
if (returnUrl == null)
returnUrl = "/";
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
try
{
UserRepository _userRepository = new UserRepository();
var usr = _userRepository.GetUserLoginDetial(model);
if (usr != null)
{
RoleRepository roleRepo = new RoleRepository();
List userRolesAccess = roleRepo.GetUserRolesListByUserId(usr.Id);
List module = roleRepo.GetModuleAccessByUserId(usr.Id);
if (userRolesAccess.Any())
{
SessionHelper.SetUserRoles(userRolesAccess);
SessionHelper.SetUserModuleAccess(module);
SessionHelper.SetUserSession(usr);
}
else
{
ViewBag.ReturnUrl = returnUrl;
ViewBag.Message = "Username/password is incorrent or roles are not defined. Please try again!";
return View(model);
}
try
{
//ActivityLogRepository Alr = new ActivityLogRepository();
//ActivityLog ActivityLogObj = new ActivityLog
//{
// Description = string.Format("{0} {1} logged in.", usr.FirstName, usr.LastName),
// Project = 0 //0 represent login/root of project
//};
//Alr.AddActivity(ActivityLogObj);
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "", "Dashboard", "AccountController", "GetStockDetail(Inner Block)");
}
return Redirect(returnUrl);
}
else
{
ViewBag.ReturnUrl = returnUrl;
ViewBag.Message = "Username or password incorrent. Please try again!";
return View(model);
}
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "", "Dashboard", "AccountController", "GetStockDetail(Outer Block)");
ViewBag.Message = ex.Message;
}
return View(model);
}
public JsonResult ForgotPassword(User user)
{
try
{
int success = 0;
UserRepository _userRepository = new UserRepository();
var usr = _userRepository.GetActiveUserDetailByFilter(user);
if (usr != null)
{
success = 1;
try
{
string body = "Email: " + usr.Email + "Password: " + usr.Password;
EmailHelper.SendEmail(
usr.Email,
"",
"Dashboard Forgot Password Notification",
body
);
success = 1;
}
catch (Exception ex)
{
ErrorLogRepository.logError(ex, "", "Dashboard", "AccountController", "ForgotPassword(Inner Block)");
throw ex;
}
}
return Json(new { success }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "", "Dashboard", "AccountController", "ForgotPassword(Outer Block)");
throw ex;
}
}
public ActionResult LogOff()
{
Session.Abandon();
Session.Clear();
return RedirectToAction("Login", "Account");
}
}
}
Account view named Login
@model RDX.Domain.Entities.User
@{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_LoginLayout.cshtml";
}
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "login100-form validate-form flex-sb flex-w" }))
{
Login
@Html.TextBoxFor(t => t.Email, new { Type = "email", @class = "input100", @name = "username", @placeholder = "Email" })
@Html.TextBoxFor(t => t.Password, new { Type = "password", @class = "input100", @name = "pass", @placeholder = "Password" })
Login
}
BaseController
using RDX.Domain.DTO;
using RDX.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RDX.FBATracking.Controllers
{
public class BaseController : Controller, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
if (SessionHelper.GetUserSession() != null)
{
if (CheckUserRoleAccess(filterContext) != true)
{
filterContext.Result = new RedirectResult("~/Common/AccessDenied");
}
}
else
{
//filterContext.Result = new RedirectResult(string.Format("~/HomeLogin/Login?ReturnUrl={0}", filterContext.HttpContext.Request.RawUrl));
filterContext.Result = new RedirectResult("~/Account/Login");
}
}
private bool CheckUserRoleAccess(ActionExecutingContext filterContext)
{
try
{
var controller = filterContext.RouteData.Values["controller"].ToString().ToLower();
var action = filterContext.RouteData.Values["action"].ToString().ToLower();
List roleAccessList = SessionHelper.GetUserAuthorizedRoles();
Boolean access = false;
//Super Admin
if (SessionHelper.IsUserSuperAdmin())
{
access = true;
}
//Other Users
else
{
switch (controller)
{
case "magento":
//if (roleAccessList.Where(t => t.RoleId == (int)EnumHelper.UserRole.User).FirstOrDefault() != null).FirstOrDefault() != null)
//{
// access = true;
//}
break;
}
}
return access;
}
catch (Exception ex) { throw; }
}
}
}
DHLCourierController
using RDX.Domain.DTO;
using RDX.Infrastructure.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RDX.FBATracking.Controllers
{
public class DHLCourierController : Controller
{
DHLRepository _repo = new DHLRepository();
public ActionResult List()
{
return View();
}
public JsonResult GetDHLListing(JQueryDataTableParams param, DhlDTO Filters)
{
int TotalRecords = 0;
List reportData = new List();
try
{
param.Search = Request.Form.GetValues("search[value]").FirstOrDefault();
param.SortOrder = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
param.SortColumn = int.Parse(Request.Form.GetValues("order[0][column]").FirstOrDefault().ToString());
reportData = _repo.GetList(param, Filters);
if (reportData.Any())
TotalRecords = reportData.ElementAt(0).TotalRecords;
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "CourierListing", "Courier", "CourierController", "GetList");
//throw ex;
}
return Json(new
{
draw = param.Draw,
recordsTotal = TotalRecords,
recordsFiltered = TotalRecords,
data = reportData
}, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Filter()
{
return View();
}
}
}
DHLCourier View
@{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Tracking #
Counter Status
Origin Location
Signatory Url
Date
WayBill
Destination
Piece
Location
Parcel Status
Time
Total Piece
@section scripts{
}
HomeController
using RDX.Domain.DTO;
using RDX.Infrastructure.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RDX.FBATracking.Controllers
{
public class HomeController : BaseController
{
public ActionResult Dashboard()
{
ViewBag.Message = "Welcome to our website";
return View();
}
public ActionResult AllListingStatus()
{
int success = 0;
StatusDTO data = new StatusDTO();
HomeRepository _ItemRepo = new HomeRepository();
try
{
data = _ItemRepo.DashboardAllStatus();
if (data != null)
{
success = 1;
}
}
catch (Exception ex)
{
throw ex;
}
return Json(new { success, data }, JsonRequestBehavior.AllowGet);
}
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Home view
@{
ViewBag.Title = "Dashboard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Helper.CardHeader("DHL")
@Helper.TotalStatus("lblDHLtotalRec")
@Helper.CreateProgressBar("DHLCompletedTotal", "Delivered", "DHLCompletedRec", "DHLCompletedBar")
@Helper.CardHeader("Parcel Force")
@Helper.TotalStatus("lblParcelForcetotalRec")
@Helper.CreateProgressBar("ParcelForceCompletedTotal", "Delivered", "ParcelForceCompletedRec", "ParcelForceCompletedBar")
@Helper.CardHeader("Ups")
@Helper.TotalStatus("lblUpstotalRec")
@Helper.CreateProgressBar("UpsCompletedTotal", "Delivered", "UpsCompletedRec", "UpsCompletedBar")
@section scripts{
}
Create simple library Domain
DatabaseContext
using RDX.Domain.DTO;
using RDX.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RDX.Domain.DBContext
{
public class DatabaseContext : DbContext
{
public DatabaseContext() : base("RDX_FBA_TRACKING")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();
}
public DbSet Users { get; set; }
public DbSet CourierFiles { get; set; }
public DbSet ModuleAccesses { get; set; }
public DbSet _couriers { get; set; }
public DbSet UserRoles { get; set; }
public DbSet ErrorLogs { get; set; }
public DbSet ActivityLogs { get; set; }
public DbSet DHL { get; set; }
public DbSet UPS { get; set; }
public DbSet ParcelForce { get; set; }
}
}
Create an other Library Infrastructure
UserRepository
using RDX.Domain.DBContext;
using RDX.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RDX.Infrastructure.Repository
{
public class UserRepository
{
private readonly DatabaseContext _db;
public UserRepository()
{
DatabaseContext db = new DatabaseContext();
_db = db;
}
public User GetActiveUserDetailByFilter(User filter)
{
try
{
IQueryable query = _db.Users;
if (filter.Id > 0)
query = query.Where(t => t.Id == filter.Id);
if (filter.Email != null)
query = query.Where(t => t.Email == filter.Email);
if (filter.Password != null)
{
query = query.Where(t => t.Password == filter.Password);
}
query = query.Where(t => t.IsActive == true);
return query.FirstOrDefault();
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Repository", "Infrastructure", "UserRepository", "GetActiveUserDetailByFilter");
throw ex;
}
}
public User GetUserLoginDetial(User filter)
{
try
{
User detail = _db.Users.Where(t => t.Email == filter.Email && t.Password == filter.Password && t.IsActive == true).FirstOrDefault();
if (detail != null)
{
return detail;
}
else
{
return null;
}
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Repository", "Infrastructure", "UserRepository", "GetUserLoginDetial");
throw ex;
}
}
public User GetUserDetailById(int id)
{
try
{
User detail = _db.Users.Where(t => t.Id == id && t.IsActive == true).FirstOrDefault();
if (detail != null)
{
return detail;
}
else
{
return null;
}
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Repository", "Infrastructure", "UserRepository", "GetUserDetailById");
throw ex;
}
}
public List GetAllActiveUsers()
{
try
{
return _db.Users.Where(t => t.Deleted == false).ToList();
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Repository", "Infrastructure", "UserRepository", "GetAllActiveUsers");
throw ex;
}
}
}
}
RoleRepository
using RDX.Domain.DBContext;
using RDX.Domain.DTO;
using RDX.Domain.Entities;
using RDX.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RDX.Infrastructure.Repository
{
public class RoleRepository
{private readonly DatabaseContext _db;
public RoleRepository()
{
DatabaseContext db = new DatabaseContext();
_db = db;
}
public int AddRole(UserRole role)
{
int result = 0;
try
{
role.CreatedByDate = DateTime.Now;
role.CreatedById = SessionHelper.GetUserId();
//role.Deleted = false;
_db.UserRoles.Add(role);
_db.SaveChanges();
result = role.Id;
//if (result > 0)
//{
// ActivityLogRepository Alr = new ActivityLogRepository();
// ActivityLog ActivityLogObj = new ActivityLog
// {
// Description = string.Format("{0} role added.", role.Title),
// Project = (int)EnumHelper.Project.User
// };
// Alr.AddActivity(ActivityLogObj);
//}
}
catch (Exception ex)
{
// ErrorLogRepository.logError(ex, "Users", "Infrastructure", "RoleRepository", "AddRole");
throw ex;
}
return result;
}
public List GetRolesList()
{
try
{
return _db.UserRoles.ToList();
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Users", "Infrastructure", "RoleRepository", "GetRolesList");
throw ex;
}
}
public List GetUserRolesListByUserId(int userId)
{
try
{
var list= (from userRole in _db.UserRoles
where userRole.UserId == userId
select new UserRoleDTO
{
Id = userRole.Id,
RoleId = userRole.RoleId,
UserId=userId
}).ToList();
foreach (var item in list)
{
item.Role = Enum.GetName(typeof(EnumHelper.UserRole), item.RoleId);
}
return list;
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Users", "Infrastructure", "RoleRepository", "GetUserRolesListByUserId");
throw ex;
}
}
public List GetModuleAccessByUserId(int userId)
{
try
{
var list = (from module in _db.ModuleAccesses
where module.UserId == userId
select new ModuleAccessDTO
{
Id = module.Id,
UserId=module.UserId,
ModuleId = module.ModuleId,
CreatedbyId = module.CreatedbyId,
CreatedByDate=module.CreatedByDate,
txtCreatedByDate=module.CreatedByDate.ToString(),
ModifiedById=module.ModifiedById,
ModifiedByDate=module.ModifiedByDate,
txtModifiedByDate=module.ModifiedByDate.ToString()
}).ToList();
foreach (var item in list)
{
item.Module = Enum.GetName(typeof(EnumHelper.ProjectModule), item.ModuleId);
}
return list;
}
catch (Exception ex)
{
//ErrorLogRepository.logError(ex, "Users", "Infrastructure", "RoleRepository", "GetUserRolesListByUserId");
throw ex;
}
}
public UserRole GetRoleById(int id)
{
try
{
return _db.UserRoles.Where(t => t.Id == id).FirstOrDefault();
}
catch (Exception ex) { throw ex; }
}
}
}
DHLRepository
using RDX.Domain.DBContext;
using RDX.Domain.DTO;
using RDX.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RDX.Infrastructure.Repository
{
public class DHLRepository
{
private readonly DatabaseContext _db;
public DHLRepository()
{
DatabaseContext db = new DatabaseContext();
_db = db;
}
public List List()
{
try
{
List list = _db.DHL.Select(x => new DhlDTO
{
TrackingId = x.TrackingId,
CounterStatus = x.CounterStatus,
OriginLocation = x.OriginLocation,
SignatoryUrl = x.SignatoryUrl,
Date = x.Date,
Waybill = x.Waybill,
Destination = x.Destination,
Piece = x.Piece,
Location = x.Location,
ParcelStatus = x.ParcelStatus,
Time = x.Time,
TotalPiece = x.TotalPiece,
}).ToList();
return list;
}
catch (Exception ex)
{
throw ex;
}
}
public List GetList(JQueryDataTableParams param, DhlDTO Filters)
{
List reportData = new List();
try
{
var objectContext = ((IObjectContextAdapter)_db).ObjectContext;
var command = _db.Database.Connection.CreateCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_DHLListing]";
var page = Math.Ceiling((decimal)param.start / param.length) + 1;
SqlParameter param_PageNumber = new SqlParameter("@PageNumber", SqlDbType.Int);
param_PageNumber.Direction = ParameterDirection.Input;
param_PageNumber.Value = page;
command.Parameters.Add(param_PageNumber);
SqlParameter param_RecordPerPage = new SqlParameter("@RowsPerPage", SqlDbType.Int);
param_RecordPerPage.Direction = ParameterDirection.Input;
param_RecordPerPage.Value = param.length;
command.Parameters.Add(param_RecordPerPage);
SqlParameter param_SortColumn = new SqlParameter("@SortColumn", SqlDbType.NVarChar);
param_SortColumn.Direction = ParameterDirection.Input;
param_SortColumn.Value = param.SortColumn;
command.Parameters.Add(param_SortColumn);
SqlParameter param_Sortdirection = new SqlParameter("@SortDirection", SqlDbType.NVarChar);
param_Sortdirection.Direction = ParameterDirection.Input;
param_Sortdirection.Value = param.SortOrder;
command.Parameters.Add(param_Sortdirection);
SqlParameter param_searchWord = new SqlParameter("@SearchWord", SqlDbType.NVarChar);
param_searchWord.Direction = ParameterDirection.Input;
param_searchWord.Value = param.Search;
command.Parameters.Add(param_searchWord);
SqlParameter param_Status = new SqlParameter("@Status", SqlDbType.Int);
param_Status.Direction = ParameterDirection.Input;
param_Status.Value = Filters.Status == null ? 2 : Filters.Status;
command.Parameters.Add(param_Status);
SqlParameter param_ShipmentName = new SqlParameter("@ShipmentName", SqlDbType.VarChar);
param_ShipmentName.Direction = ParameterDirection.Input;
if (Filters.ShipmentName != null)
switch (Convert.ToInt32(Filters.ShipmentName))
{
case 0:
param_ShipmentName.Value = "FBACA-1";
break;
}
else
param_ShipmentName.Value = "";
command.Parameters.Add(param_ShipmentName);
command.CommandTimeout = 0;
_db.Database.Connection.Open();
using (var reader = command.ExecuteReader())
{
var countRecord = ((IObjectContextAdapter)_db).ObjectContext.Translate(reader: reader).SingleOrDefault();
if (countRecord > 0)
{
reader.NextResult();
reportData = ((IObjectContextAdapter)_db).ObjectContext.Translate(reader: reader).Select(x => new DhlDTO
{
TrackingNumber = x.TrackingNumber,
CounterStatus = x.CounterStatus,
OriginLocation = x.OriginLocation,
SignatoryUrl = x.SignatoryUrl,
Date = x.Date,
Waybill = x.Waybill,
Destination = x.Destination,
Piece = x.Piece,
Location = x.Location,
ParcelStatus = x.ParcelStatus,
Time = x.Time,
TotalPiece = x.TotalPiece,
TotalRecords = x.TotalRecords,
}).ToList();
if (reportData.Count() > 0)
reportData.ElementAt(0).TotalRecords = countRecord;
}
}
}
catch (Exception ex)
{
ErrorLogRepository.logError(ex, "DHLListing", "Infrastructure", "DHLRepository", "GetList");
throw ex;
}
finally
{
_db.Database.Connection.Close();
}
return reportData;
}
}
}
SessionHelper
using RDX.Domain.DTO;
using RDX.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace RDX.Infrastructure.Helper
{
public class SessionHelper
{
public static void SetUserSession(User model)
{
HttpContext.Current.Session["User"] = (User)model;
}
public static User GetUserSession()
{
if (HttpContext.Current.Session["User"] != null)
{
return (User)HttpContext.Current.Session["User"];
}
else
{
return null;
}
}
public static int GetUserId()
{
if (HttpContext.Current.Session["User"] != null)
{
User session = (User)HttpContext.Current.Session["User"];
return session.Id;
}
else
{
return 0;
}
}
public static string GetUserEmail()
{
if (HttpContext.Current.Session["User"] != null)
{
User session = (User)HttpContext.Current.Session["User"];
return session.Email;
}
else
{
return "";
}
}
public static string GetUserName()
{
if (HttpContext.Current.Session["User"] != null)
{
User session = (User)HttpContext.Current.Session["User"];
return session.FirstName+" "+session.LastName;
}
else
{
return "";
}
}
public static void SetUserRoles(List userRolesAccess)
{
HttpContext.Current.Session["UserRoleAccess"] = (List)userRolesAccess;
}
public static void SetUserModuleAccess(List userRolesAccess)
{
HttpContext.Current.Session["UserModuleAccess"] = (List)userRolesAccess;
}
public static List GetUserAuthorizedRoles()
{
if (HttpContext.Current.Session["UserRoleAccess"] != null)
{
List roleAccessList = (List)HttpContext.Current.Session["UserRoleAccess"];
return roleAccessList;
}
else
{
return null;
}
}
public static List GetUserModuleAccess()
{
if (HttpContext.Current.Session["UserModuleAccess"] != null)
{
List roleAccessList = (List)HttpContext.Current.Session["UserModuleAccess"];
return roleAccessList;
}
else
{
return null;
}
}
public static bool IsUserSuperAdmin()
{
if (HttpContext.Current.Session["UserRoleAccess"] != null)
{
List roleAccessList = (List)HttpContext.Current.Session["UserRoleAccess"];
UserRoleDTO roleDetail = roleAccessList.Where(t => t.RoleId == 1).FirstOrDefault();
if (roleDetail != null)
return true;
else
return false;
}
else
{
return false;
}
}
public static int GetUserRoleAccess(int projectId)
{
if (HttpContext.Current.Session["UserRoleAccess"] != null)
{
List roleAccessList = (List)HttpContext.Current.Session["UserRoleAccess"];
List roleAccess = roleAccessList.Where(role => role.RoleId == projectId).ToList();
if (roleAccess.Any())
return (int)roleAccess.ElementAt(0).RoleId;
else
return 0;
}
else
{
return 0;
}
}
}
}
CommonHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace RDX.Infrastructure.Helper
{
public class CommonHelper
{
#region Http Request
public static string GetUserAgent()
{
var a = HttpContext.Current.Request.UserAgent;
return a;
}
public static string GetUserIp()
{
string ipAdd = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAdd))
{
ipAdd = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ipAdd;
}
#endregion
public static string storeUrl(string store)
{
Dictionary url = new Dictionary();
url["UK"] = "https://rdxsports.co.uk/";
url["US"] = "https://rdxsports.com/";
url["AU"] = "https://rdxsports.com.au/";
url["INT"] = "https://global.rdxsports.com/";
url["FR"] = "https://rdxsports.fr/";
url["IT"] = "https://rdxsports.it/";
url["PT"] = "https://rdxsports.pt/";
url["EU"] = "https://rdxsports.eu/";
url["ES"] = "https://rdxsports.es/";
url["DE"] = "https://rdxsports.de/";
url["RU"] = "https://rdxsports.com.ru/";
url["RUEN"] = "https://rdxsports.com.ru/";
return url[store];
}
}
}
Comments
Post a Comment