using LoggingHelper; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Net; using GODATA.Models.Tracking; using System.Configuration; using GODATA.Models.Calcuation; using Microsoft.Practices.EnterpriseLibrary.Logging; using System.Globalization; using System.Data; using ExcelHelper; using ExportToExcel; namespace GODATA.Controllers { /// /// class that contains all the tracking related methods (Live/History Tracking) /// [GODATA.MvcApplication.SessionExpire] public class TrackingController : Controller { #region Global Variables /// /// Represent object of LoggingUtility class /// LoggingUtility objLog = new LoggingUtility(); /// /// Represent string object contain log file path /// //string path = "~/Log/"; string path = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PathLog"]); /// /// Represent string object contain log status /// string logtf = (ConfigurationManager.AppSettings["Log"]); /// /// Represent string object contain Error log status /// string errorlogtf = (ConfigurationManager.AppSettings["ErrorLog"]); /// /// getting user's utc minutes from session /// private static string _timeOffSetMinutes = null; /// /// getting login user's id /// private static string _LoginUserId = null; /// /// /// private static string _TimeZoneId = ConfigurationManager.AppSettings["TimeZoneId"].ToString(); /// /// URI to Path to Excel Export location. /// private static string _exportLocation = ConfigurationManager.AppSettings["excelExportPath"].ToString(); /// /// Absolute Path on server in which excel files are saved /// private static string _excelExportPathOnServer = ConfigurationManager.AppSettings["excelExportPathOnServer"].ToString(); /// /// getting date time format from AppSetting in web.config file /// private static string _dateTimeFormat = ConfigurationManager.AppSettings["dateTimeFormat"].ToString(); #endregion /// /// An attribute to allow CORS (Cross-site HTTP requests) /// public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*"); base.OnActionExecuting(filterContext); } } /// /// To show main page of Tracking /// /// main page of Tracking [AllowCrossSiteJson] public ActionResult Index() { return View(); } #region Manage Live Tracking /// /// To show main page of Live Tracking /// /// main page of Live Tracking [AllowCrossSiteJson] public ActionResult LiveTracking() { objLog.AddLogFile("Tracking_Live", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); try { _LoginUserId = Session["UserId"].ToString(); _timeOffSetMinutes = Session["UtcMinute"].ToString(); ViewBag.SecurityToken = ConfigurationManager.AppSettings["RESTfulSecurityToken"].ToString(); ViewBag.UtcMinutes = _timeOffSetMinutes; ViewBag.Userid = _LoginUserId; ViewBag.UserRole = Session["UserRole"].ToString(); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); return View(); } catch (Exception ex) { objLog.ErrorLogFile("Tracking_Live", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); throw ex; } } /// /// Exports Timeslot Closure report /// /// security token /// UTC minutes /// user id /// start date /// end date /// state name /// city name /// dealer id /// generated report path //[HttpPost] //public string ExportReport(string vanState, string vanCity, string dealerName) //{ // try // { // //Getting login user's id, name and utc minutes from session // _LoginUserId = Session["UserId"].ToString(); // //_LoginUserName = Session["UserName"].ToString(); // int timeOffSetMinutes = Convert.ToInt32(Session["UtcMinute"]); // string securityToken = ConfigurationManager.AppSettings["RESTfulSecurityToken"].ToString(); // TrackingRepository oReportRepository = new TrackingRepository(); // LiveTrackingModel model = new LiveTrackingModel(); // model = oReportRepository.GetLiveTrackingReport(securityToken, timeOffSetMinutes, _LoginUserId, vanState, vanCity, dealerName); // //=======================Model Mnaupulatin======================== // foreach (ListUser user in model.ListUsers) // { // // Making EOS team name // string dealername = (user.DealerDealerName == null) ? "" : user.DealerDealerName.ToString(); // string serviceEngName = (user.ServiceEngineerName == null) ? "" : user.ServiceEngineerName.ToString(); // user.EOSteam = dealername + " (" + serviceEngName + ')'; // // initializing the battery status // user.BatteryStatus = "0 %"; // // Geeting tracked user and putting the live values into it. // foreach (ListTracking trackedUser in model.ListTracking) // { // string trackedUserDeviceAlias = (trackedUser.DeviceAlias == null) ? "" : trackedUser.DeviceAlias.ToString(); // if (user.ServiceEngineerDeviceAlias.ToString() == trackedUserDeviceAlias) // { // string isConnected = (trackedUser.IsConnected == null) ? "false" : trackedUser.IsConnected.ToString(); // user.IsConnected = (isConnected.ToUpper() == "FALSE") ? "OFFLINE" : "ONLINE"; // user.Message = Convert.ToDateTime(trackedUser.LogTime).ToString(_dateTimeFormat); // user.BatteryStatus = trackedUser.BatteryStatus + " %"; // //user.GpsStatus = trackedUser.GpsStatus; // //user.IsCharging = (trackedUser.IsCharging.ToString().ToUpper() == "FALSE" ? "NOT CHARGING" : "CHARGING"); // } // } // // replacing all the falses with OFFLINE // user.IsConnected = (user.IsConnected.ToString().ToUpper() == "FALSE") ? "OFFLINE" : user.IsConnected; // } // List sortedUserList = model.ListUsers.OrderByDescending(o => o.IsConnected).ToList(); // //================================================================ // DataTable liveTrackingReport = new DataTable(); // if (sortedUserList != null) // { // liveTrackingReport = sortedUserList.ToDataTable(); // liveTrackingReport.Columns.RemoveAt(0); // liveTrackingReport.AcceptChanges(); // } // // getting required dataset // DataSet ds = new DataSet(); // ds.Tables.Add(liveTrackingReport); // //================================ Excel Functionality ===================================// // ExcelUtility objExcelUtility = new ExcelHelper.ExcelUtility(); // List workbokkMapping = new List(); // if (ds.Tables[0].Rows.Count > 0) // { // workbokkMapping.Add(new WorkbookMappingModel { DataTableName = ds.Tables[0].TableName, WorkSheetName = "Live_Tracking", StartColumnName = "B", StartRowNumber = 5, WorkSheetNumber = 1, AutoFit = true }); // } // string filename = "LiveTrackingReport_" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".xlsx"; // string pathToExcelFile = _exportLocation + filename; // string templatePath = Server.MapPath(ConfigurationManager.AppSettings["LiveTrackingTemplate"].ToString()); ; // string saveAs = Server.MapPath(_excelExportPathOnServer + filename); // ExcelHelper.StatusModel result = objExcelUtility.ExportToExcel(ds, templatePath, workbokkMapping, saveAs, false); // //================================ Excel Functionality End ===================================// // // returning path to generated Excel file // if (result.Status == 1) { return pathToExcelFile; } // else { return "error"; } // } // catch (Exception ex) // { // objLog.ErrorLogFile("LiveTracking_ExportReport", ex.Message, path, errorlogtf); // return "error"; // } //} #endregion #region Manage Histroy Tracking /// /// To show main page of HistoryTracking /// /// main page of HistoryTracking [AllowCrossSiteJson] public ActionResult HistoryTracking() { objLog.AddLogFile("Tracking_History", DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); try { _LoginUserId = Session["UserId"].ToString(); _timeOffSetMinutes = Session["UtcMinute"].ToString(); ViewBag.SecurityToken = ConfigurationManager.AppSettings["RESTfulSecurityToken"].ToString(); ViewBag.UtcMinutes = _timeOffSetMinutes; ViewBag.Userid = _LoginUserId; objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); return View(); } catch (Exception ex) { objLog.ErrorLogFile("Tracking_History", ex.Message, path, errorlogtf); objLog.AddLogFile(DateTime.Now.ToString(ConfigurationManager.AppSettings["dateTimeFormat"]), path, logtf); throw ex; } } /// /// Function used to get coler code according to number of path. /// /// Index /// Color code [AllowCrossSiteJson] private JsonResult GetPathColorCode(int index) { string[] colorCode = { "#633ebe", "#2878ed", "#db552d", "#bb1d48", "#00a31b" }; if (index > 1) { index = index % colorCode.Length; return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { success = true, result = index } }; } else { return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { success = false } }; } } #endregion /// /// The popup for Showing Dealer Map /// returns PartialView for showing Dealer Map /// public ActionResult WorkingHours(string van_start_working_hours, string van_end_working_hours) { ViewBag.vanStartWorkingHours = van_start_working_hours; ViewBag.vanEndWorkingHours = van_end_working_hours; return PartialView(); } [HttpPost] public string ExportReport(string vanState, string vanCity, string dealerName) { try { //Getting login user's id, name and utc minutes from session _LoginUserId = Session["UserId"].ToString(); //_LoginUserName = Session["UserName"].ToString(); int timeOffSetMinutes = Convert.ToInt32(Session["UtcMinute"]); string securityToken = ConfigurationManager.AppSettings["RESTfulSecurityToken"].ToString(); TrackingRepository oReportRepository = new TrackingRepository(); LiveTrackingModel model = new LiveTrackingModel(); model = oReportRepository.GetLiveTrackingReport(securityToken, timeOffSetMinutes, _LoginUserId, vanState, vanCity, dealerName); //=======================Model Mnaupulatin======================== foreach (ListUser user in model.ListUsers) { // Making EOS team name string dealername = (user.DealerDealerName == null) ? "" : user.DealerDealerName.ToString(); string serviceEngName = (user.ServiceEngineerName == null) ? "" : user.ServiceEngineerName.ToString(); user.EOSteam = dealername + " (" + serviceEngName + ')'; // initializing the battery status user.BatteryStatus = "0 %"; // Geeting tracked user and putting the live values into it. foreach (ListTracking trackedUser in model.ListTracking) { string trackedUserDeviceAlias = (trackedUser.DeviceAlias == null) ? "" : trackedUser.DeviceAlias.ToString(); if (user.ServiceEngineerDeviceAlias.ToString() == trackedUserDeviceAlias) { string isConnected = (trackedUser.IsConnected == null) ? "false" : trackedUser.IsConnected.ToString(); user.IsConnected = (isConnected.ToUpper() == "FALSE") ? "OFFLINE" : "ONLINE"; user.Message = Convert.ToDateTime(trackedUser.LogTime).ToString(_dateTimeFormat); user.BatteryStatus = trackedUser.BatteryStatus + " %"; //user.GpsStatus = trackedUser.GpsStatus; //user.IsCharging = (trackedUser.IsCharging.ToString().ToUpper() == "FALSE" ? "NOT CHARGING" : "CHARGING"); } } // replacing all the falses with OFFLINE user.IsConnected = (user.IsConnected.ToString().ToUpper() == "FALSE") ? "OFFLINE" : user.IsConnected; } List sortedUserList = model.ListUsers.OrderByDescending(o => o.IsConnected).ToList(); //================================================================ DataTable liveTrackingReport = new DataTable(); if (sortedUserList != null) { liveTrackingReport = sortedUserList.ToDataTable(); liveTrackingReport.Columns.RemoveAt(0); liveTrackingReport.Columns.RemoveAt(liveTrackingReport.Columns.Count - 2); liveTrackingReport.Columns.RemoveAt(liveTrackingReport.Columns.Count - 2); liveTrackingReport.AcceptChanges(); } // getting required dataset DataSet ds = new DataSet(); ds.Tables.Add(liveTrackingReport); //================================ Excel Functionality ===================================// ExcelUtility objExcelUtility = new ExcelHelper.ExcelUtility(); List workbokkMapping = new List(); if (ds.Tables[0].Rows.Count > 0) { workbokkMapping.Add(new WorkbookMappingModel { DataTableName = ds.Tables[0].TableName, WorkSheetName = "Live_Tracking", StartColumnName = "B", StartRowNumber = 5, WorkSheetNumber = 1, AutoFit = true }); } string filename = "LiveTrackingReport_" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".xlsx"; string pathToExcelFile = _exportLocation + filename; string templatePath = Server.MapPath(ConfigurationManager.AppSettings["LiveTrackingTemplate"].ToString()); ; string saveAs = Server.MapPath(_excelExportPathOnServer + filename); bool isCreated = CreateExcelFile.CreateExcelDocument(ds, saveAs); // ExcelHelper.StatusModel result = objExcelUtility.ExportToExcel(ds, templatePath, workbokkMapping, saveAs, false); //================================ Excel Functionality End ===================================// if (isCreated == true) { return pathToExcelFile; } else { return "error"; } // returning path to generated Excel file } catch (Exception ex) { objLog.ErrorLogFile("LiveTracking_ExportReport", ex.Message, path, errorlogtf); return "error"; } } } }