namespace VECV_WebApi.Models.EmailServices { #region Namespaces using DBHelper; using LoggingHelper; using Npgsql; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Web; using System.Web.Script.Serialization; using System.Xml; using System.Xml.Linq; using VECV_WebApi.Models.Authorization; using VECV_WebApi.Models.Customer; using VECV_WebApi.Models.Dealer; using VECV_WebApi.Models.ServiceEngineer; using RestSharp; using RestSharp.Deserializers; using VECV_WebApi.Models.Ticket; using Newtonsoft.Json.Linq; using VECV_WebApi.Common; using Newtonsoft.Json; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Net.Security; #endregion #region Repository Class /// /// This class contain global used method details /// public class GlobalRepository { #region Global Variables /// /// making object of LoggingUtility class available to this class /// LoggingUtility objLog = new LoggingUtility(); /// /// making the data-log file path available to this class /// string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PathLog"]); /// /// making error log file path available to this class /// string errorlogtf = (ConfigurationManager.AppSettings["ErrorLog"]); /// /// making the Database connection string available to this class /// private string _connStr; /// /// making Authentication Repository object available to this class /// AuthenticationRepository objAuthorization; #endregion #region Contructors /// /// Default constructor intialize connection string of vecv database /// public GlobalRepository(string connString) { this._connStr = connString; } #endregion #region API Methods /// /// To get all region list /// /// all region list public List GetAllRegionList() { List objList = new List(); RegionModel objModel = new RegionModel(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_region"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new RegionModel { RegionName = s.Field("_region") }).ToList(); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllRegionList", Ex.Message, path, errorlogtf); return objList; } } /// /// To get all TimeZone list /// /// all TimeZone list public DealerDetailModel ReleaseIMEI(string IMEI) { DataSet dsRemoveServiceDeiceCredential = new DataSet(); TimeZoneModel objModel = new TimeZoneModel(); DealerDetailModel objDealerDetailModel = new DealerDetailModel(); try { NpgsqlParameter[] nSqlParamServiceDeiceCredential = new NpgsqlParameter[1]; nSqlParamServiceDeiceCredential[0] = new NpgsqlParameter("inimei_number", IMEI); dsRemoveServiceDeiceCredential = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_release_service_engg_device_credentials_imei_number"], nSqlParamServiceDeiceCredential); objDealerDetailModel.Status = dsRemoveServiceDeiceCredential.Tables[0].Rows[0][0].ToString(); return objDealerDetailModel; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objLog.ErrorLogFile("GlobalRepository ReleaseIMEI", Ex.Message, path, errorlogtf); throw Ex; } } /// /// To get all TimeZone list /// /// all TimeZone list public List GetAllTimeZoneList() { List objList = new List(); TimeZoneModel objModel = new TimeZoneModel(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_timezone_info"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TimeZoneModel { TimeZoneId = s.Field("timezone_id"), TimeZoneName = s.Field("display_name"), UtcMinute = s.Field("offset_in_minutes"), DisplayId = s.Field("display_id"), }).ToList(); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllTimeZoneList", Ex.Message, path, errorlogtf); return objList; } } /// /// To get all State list /// /// state info /// all State list public List GetAllStateList(StateModel model) { List objList = new List(); StateModel objModel = new StateModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_state"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new StateModel { StateId = s.Field("state_id"), StateAlias = s.Field("state_alias") }).ToList(); } } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllStateList", Ex.Message, path, errorlogtf); return objList; } } /// /// To get all State list Region Wise /// /// state info /// all State list public List GetAllStateListRegionWise(OrgganizationModel model) { List objList = new List(); StateModel objModel = new StateModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inregion_id ", model.Id); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_state_region_wise"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new StateModel { StateId = s.Field("state_id"), StateAlias = s.Field("state_alias") }).ToList(); } } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllStateListRegionWise", Ex.Message, path, errorlogtf); return objList; } } /// /// To get all City List State Id Wise /// /// state info /// all City List State Id Wise public List GetAllCityListStateIdWise(CityModel model) { List objList = new List(); CityModel objModel = new CityModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("instate_id ", model.StateId); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_city_state_wise"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new CityModel { CityId = s.Field("city_id"), CityName = s.Field("city_alias") }).ToList(); } } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllCityListStateIdWise", Ex.Message, path, errorlogtf); return objList; } } /// /// To get all Organization List User Id Wise /// /// user info /// all Organization List User Id Wise public List GetAllOrganizationListUserIdWise(OrgganizationModel model) { List objList = new List(); OrgganizationModel objModel = new OrgganizationModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inuserid ", model.Id); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_organization_user_wise"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new OrgganizationModel { OrganizationName = s.Field("_organization_name"), Region = s.Field("_region"), Id = s.Field("_id") }).ToList(); } } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllOrganizationListUserIdWise", Ex.Message, path, errorlogtf); return objList; } } /// /// To get all Organization all Vehicle Type List /// /// all Organization all Vehicle Type List public List GetAllVehicleTypeList() { try { DataSet ds = new DataSet(); List objList = new List(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_vehicle_model"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new VehicleTypeModel { VehicleTypeId = s.Field("id"), VehicleTypeName = s.Field("name"), VehicleTypeTagging = s.Field("tagging"), IsDeleted = s.Field("is_deleted"), udanVehicleProductId = s.Field("udanVehicleProductId"), udanVehicleProductName = s.Field("udanVehicleProductName") }).ToList(); } return objList; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllVehicleTypeList", Ex.Message, path, errorlogtf); throw Ex; } } public List GetAllVehicleTypeListByFuelType(string fueltype) { try { DataSet ds = new DataSet(); List objList = new List(); // ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_vehicle_model"]); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("infueltype ", fueltype); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_vehicle_model_fuel_type"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new VehicleTypeModel { VehicleTypeId = s.Field("id"), VehicleTypeName = s.Field("name"), VehicleTypeTagging = s.Field("tagging"), IsDeleted = s.Field("is_deleted"), udanVehicleProductId = s.Field("udanVehicleProductId"), udanVehicleProductName = s.Field("udanVehicleProductName") }).ToList(); } return objList; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllVehicleTypeList", Ex.Message, path, errorlogtf); throw Ex; } } public Telematic_Model ChassisTelematicDetail(string Chassis) { string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGTELEMATICDATA"].ToString(), Chassis); try { Telematic_Model model = new Telematic_Model(); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.Created) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); model = js.Deserialize(res); } return model; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository ChassisTelematicDetail " + APIRegistrationNo, Ex.Message, path, errorlogtf); throw Ex; } } /* public async Task getTelematics(string chssis_no) { Telematic_Model objTelematic_Model = new Telematic_Model(); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, ConfigurationManager.AppSettings["EOSAPIFORGETTINGTELEMATICDATA"].ToString()); // Username and password for Basic Authentication var username = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGTELEMATICDATA"].ToString(); var password = ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGTELEMATICDATA"].ToString(); var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); return objTelematic_Model; }*/ public async Task getTelematics(string chssis_no) { Telematic_Model objTelematic_Model = new Telematic_Model(); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, ConfigurationManager.AppSettings["EOSAPIFORGETTINGTELEMATICDATA"].ToString()); // Username and password for Basic Authentication var username = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGTELEMATICDATA"].ToString(); var password = ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGTELEMATICDATA"].ToString(); var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); try { var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { string errorContent = await response.Content.ReadAsStringAsync(); TicketRepository objTicketRepository = new TicketRepository(_connStr); bool isSend = objTicketRepository.emailForError($"HTTP {(int)response.StatusCode}: {response.ReasonPhrase}", "getTelematics"); objLog.ErrorLogFile("getTelematics", errorContent, path, errorlogtf); return null; // or handle fallback } response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); } catch (HttpRequestException ex) { TicketRepository objTicketRepository = new TicketRepository(_connStr); bool isSend = objTicketRepository.emailForError("HTTP Request failed: " + ex.Message, "getTelematics"); objLog.ErrorLogFile("getTelematics", ex.Message, path, errorlogtf); } return objTelematic_Model; } public CustomerModel checkRegistartionNoandGetDetail(CustomerModel model) { try { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[2]; nSqlParam[0] = new NpgsqlParameter("inregistration_number", model.VehicleRegistrationNumber); nSqlParam[1] = new NpgsqlParameter("inchassis_number", model.VehicleNumberPlate); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_detail_By_DBM"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { model.VehicleRegistrationNumber = ds.Tables[0].Rows[0]["_vehicle_registration_number"].ToString(); model.VehicleNumberPlate = ds.Tables[0].Rows[0]["vehicle_number_plate"].ToString(); model.VehicleModelNumber = ds.Tables[0].Rows[0]["_customer_vehicle_model_name"].ToString(); model.VehicleType = ds.Tables[0].Rows[0]["_vehicle_type"].ToString(); model.CustomerCustomerName = ds.Tables[0].Rows[0]["_customer_customer_name"].ToString(); model.CustomerMobileNumber1 = ds.Tables[0].Rows[0]["_customer_mobile_number_1"].ToString(); model.CustomerEmailId = ds.Tables[0].Rows[0]["_customer_mobile_number_1"].ToString(); model.CustomerAddress = ds.Tables[0].Rows[0]["_customer_address"].ToString(); model.CustomerState = ds.Tables[0].Rows[0]["_customer_state"].ToString(); model.CustomerCity = ds.Tables[0].Rows[0]["_customer_city"].ToString(); if (ds.Tables[0].Rows[0]["_customer_id"].ToString() == null) { model.CustomerId = ""; } else { model.CustomerId = ds.Tables[0].Rows[0]["_customer_id"].ToString(); } model.CustomerType = ds.Tables[0].Rows[0]["_customer_type"].ToString(); } else { model.CustomerType = ""; } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkRegistartionNoandGetDetail", Ex.Message, path, errorlogtf); throw Ex; } return model; } public CustomerModel checkChassisNoandGetDetail(CustomerModel model) { try { String result = model.VehicleRegistrationNumber.Substring(model.VehicleRegistrationNumber.Length - 6); DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[2]; nSqlParam[0] = new NpgsqlParameter("inregistration_number ", null); nSqlParam[1] = new NpgsqlParameter("inchassis_number ", result); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_detail_By_DBM"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { model.VehicleRegistrationNumber = ds.Tables[0].Rows[0]["_vehicle_registration_number"].ToString(); model.VehicleNumberPlate = ds.Tables[0].Rows[0]["vehicle_number_plate"].ToString(); } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkChassisNoandGetDetail", Ex.Message, path, errorlogtf); throw Ex; } return model; } public CustomerModel checkChassisNoandGetDetailEPS(CustomerModel model) { try { // String result = model.VehicleRegistrationNumber.Substring(model.VehicleRegistrationNumber.Length - 6); DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inengine_number ", model.VehicleNumberPlate); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_valid_engine_number_eps"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { // model.VehicleRegistrationNumber = ds.Tables[0].Rows[0]["_vehicle_registration_number"].ToString(); model.VehicleNumberPlate = ds.Tables[0].Rows[0]["sp_valid_engine_number_eps"].ToString(); } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkChassisNoandGetDetail", Ex.Message, path, errorlogtf); throw Ex; } return model; } public CustomerModel checkChassisNoandGetDetailpreclosure(CustomerModel model) { TicketRepository objTicketRepository = new TicketRepository(_connStr); string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), "", model.VehicleRegistrationNumber.ToUpper()); try { WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); model.VehicleRegistrationNumber = tempElement.Value; model.VehicleNumberPlate = tempElement.Value;//Chassis Number } } } catch (Exception Ex) { bool isSend = objTicketRepository.emailForError(Ex.Message, APIRegistrationNo); objLog.ErrorLogFile("GlobalRepository checkChassisNoandGetDetailpreclosure " + APIRegistrationNo, Ex.Message, path, errorlogtf); throw Ex; } return model; } /* public CustomerModel checkChassisNoandGetDetailpreclosure(CustomerModel model) { string APIRegistrationNo = string.Format( ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), "", model.VehicleRegistrationNumber.ToUpper() ); TicketRepository objTicketRepository = new TicketRepository(_connStr); try { var clientVehicleType = new RestClient(APIRegistrationNo) { Timeout = 10000 }; var requestVehicleType = new RestRequest(Method.GET); // Configure security protocols ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; // Basic authentication var username = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(); var password = ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")); requestVehicleType.AddHeader("Authorization", $"Basic {credentials}"); requestVehicleType.AddHeader("Accept", "application/xml"); requestVehicleType.AddHeader("Content-Type", "application/xml"); IRestResponse responseVehicleType = clientVehicleType.Execute(requestVehicleType); // Handle connection or timeout errors if (responseVehicleType.ResponseStatus == ResponseStatus.Error || responseVehicleType.ResponseStatus == ResponseStatus.TimedOut) { bool isSendemail = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); model.Status = "2"; model.Message = "API error or timeout occurred."; return model; } // Handle Unauthorized if (responseVehicleType.StatusCode == HttpStatusCode.Unauthorized) { bool isSendEmail = objTicketRepository.emailForError("API Login Failed: Unauthorized.", clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), "API Login Failed: Unauthorized.", path, errorlogtf); model.Status = "2"; model.Message = "Unauthorized API access."; return model; } // Handle BadRequest or NotFound if (responseVehicleType.StatusCode == HttpStatusCode.BadRequest || responseVehicleType.StatusCode == HttpStatusCode.NotFound) { model.Status = "2"; model.Message = "Invalid chassis number or request."; //bool isSendemail = objTicketRepository.emailForError($"API returned {responseVehicleType.StatusCode}: {responseVehicleType.Content}", APIRegistrationNo); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), $"API returned {responseVehicleType.StatusCode}: {responseVehicleType.Content}", path, errorlogtf); return model; } // Handle OK response if (responseVehicleType.StatusCode == HttpStatusCode.OK) { byte[] bytes = Encoding.Default.GetBytes(responseVehicleType.Content); string res = Encoding.UTF8.GetString(bytes); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; if (nodeList.Count == 0) { model.Status = "2"; model.Message = "No data found for the given chassis number."; return model; } foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); if (tempElement != null) { model.VehicleRegistrationNumber = tempElement.Value; model.VehicleNumberPlate = tempElement.Value; // Chassis Number model.Status = "1"; model.Message = "Data retrieved successfully."; } else { model.Status = "2"; model.Message = "Chassis number data not found in response."; } } return model; } // If response is something else unexpected model.Status = "2"; model.Message = $"Unexpected API response: {responseVehicleType.StatusCode}"; // bool isSend = objTicketRepository.emailForError($"Unexpected API response: {responseVehicleType.StatusCode} - {responseVehicleType.Content}", APIRegistrationNo); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), $"Unexpected API response: {responseVehicleType.StatusCode} - {responseVehicleType.Content}", path, errorlogtf); return model; } catch (Exception ex) { bool isSend = objTicketRepository.emailForError(ex.Message, APIRegistrationNo); objLog.ErrorLogFile("GlobalRepository checkChassisNoandGetDetailpreclosure " + APIRegistrationNo, ex.Message, path, errorlogtf); throw; // preserve stack trace } }*/ /* public CustomerModel checkChassisNoandGetDetailpreclosure(CustomerModel model) { string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), "", model.VehicleRegistrationNumber.ToUpper()); try { var clientVehicleType = new RestClient(APIRegistrationNo); clientVehicleType.Timeout = 10000; var requestVehicleType = new RestRequest(Method.GET); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; var username = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(); var password = ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); // Add Basic Authentication var credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")); // Add Basic Authentication header requestVehicleType.AddHeader("Authorization", $"Basic {credentials}"); requestVehicleType.AddHeader("Accept", "application/xml"); requestVehicleType.AddHeader("Content-Type", "application/xml"); IRestResponse responseVehicleType = clientVehicleType.Execute(requestVehicleType); TicketRepository objTicketRepository = new TicketRepository(_connStr); if (responseVehicleType.ResponseStatus.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.ResponseStatus.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.OK) { byte[] bytes = Encoding.Default.GetBytes(responseVehicleType.Content); string res = Encoding.UTF8.GetString(bytes); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); model.VehicleRegistrationNumber = tempElement.Value; model.VehicleNumberPlate = tempElement.Value;//Chassis Number } } else { // bool isSend = objTicketRepository.emailForError(responseVehicleType.StatusCode.ToString(), clientVehicleType.BaseUrl.ToString()); // objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); model.Status = "2"; model.Message = "invalid chassis"; } } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkChassisNoandGetDetailpreclosure " + APIRegistrationNo, Ex.Message, path, errorlogtf); throw Ex; } return model; }*/ public List getEngineBysuggestion(Engine_SRCH_Model model) { List objList = new List(); if (model.EngineSearch == null) { } else { CustomerModel objModelCustomerModel = new CustomerModel(); objModelCustomerModel.VehicleNumberPlate = model.EngineSearch; //objModelCustomerModel = objGlobalRepository.checkChassisNoandGetDetailEPS(objModelCustomerModel); List objCustomerList = new List(); objCustomerList = checkChassisNoandGetCustomerDetailEPS(objModelCustomerModel); //if (objModelCustomerModel.VehicleNumberPlate != "" || (objModelCustomerModel.VehicleNumberPlate != null)) if (objCustomerList.Count > 0) { /*model.EngineNo = objModelCustomerModel.VehicleNumberPlate;   model.ChassisNo = objModelCustomerModel.VehicleNumberPlate;   model.VehicleType = "EPS";\*/ foreach (var customer in objCustomerList) { Engine_SRCH_Model resultModel = new Engine_SRCH_Model { ChassisNo = customer.VehicleRegistrationNumber, EngineNo = customer.VehicleRegistrationNumber, VehRegNo = customer.VehicleRegistrationNumber, // Use appropriate property if different VehicleType = "EPS" }; objList.Add(resultModel); } } } return objList; } /* public List getChassisBysuggestion(CHASSIS_SRCH_Model model) { List objList = new List(); if (model.ChassisSearch == null) { } else { string APIChassisSearch = string.Format(ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH"].ToString(), model.ChassisSearch.ToUpper()); try { //CHASSIS_SRCH_Model objChassis = new CHASSIS_SRCH_Mode(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebRequest req = WebRequest.Create(APIChassisSearch); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString(), ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString()); WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); model.ChassisNo = tempElement.Value; tempElement = doc.Descendants(ab + "RegNo").FirstOrDefault(); model.VehRegNo = tempElement.Value; // vehicle type logic - if Modline is blank then VT is H else type is Tipper tempElement = doc.Descendants(ab + "Modline").FirstOrDefault(); model.VehicleType = tempElement.Value != "" & tempElement.Value != null ? "Tipper" : "Haulage"; objList.Add(new CHASSIS_SRCH_Model() { VehRegNo = model.VehRegNo, ChassisNo = model.ChassisNo, VehicleType = model.VehicleType }); // model.VehicleNumberPlate = tempElement.Value;//Chassis Number } } } catch (Exception Ex) { objList.Add(new CHASSIS_SRCH_Model() { Status = "0" }); // objList.Status = "0"; //objModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository getChassisBysuggestion" + APIChassisSearch, Ex.Message, path, errorlogtf); return objList; } } return objList; }*/ public List getChassisBysuggestion(CHASSIS_SRCH_Model model) { List objList = new List(); if (model.ChassisSearch == null) { } else { string APIChassisSearch = string.Format(ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH"].ToString(), model.ChassisSearch.ToUpper()); try { //CHASSIS_SRCH_Model objChassis = new CHASSIS_SRCH_Mode(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebRequest req = WebRequest.Create(APIChassisSearch); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString(), ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString()); WebResponse webRes = req.GetResponse(); TicketRepository objTicketRepository = new TicketRepository(_connStr); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(resp.StatusCode.ToString(), APIChassisSearch.ToString()); objLog.ErrorLogFile(APIChassisSearch, resp.StatusCode.ToString(), path, errorlogtf); } else { if (resp.StatusCode.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(resp.StatusCode.ToString(), APIChassisSearch.ToString()); objLog.ErrorLogFile(APIChassisSearch, resp.StatusCode.ToString(), path, errorlogtf); } else { if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", APIChassisSearch.ToString()); objLog.ErrorLogFile(APIChassisSearch, "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else if (resp.StatusCode == System.Net.HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); model.ChassisNo = tempElement.Value; tempElement = doc.Descendants(ab + "RegNo").FirstOrDefault(); model.VehRegNo = tempElement.Value; // vehicle type logic - if Modline is blank then VT is H else type is Tipper tempElement = doc.Descendants(ab + "Modline").FirstOrDefault(); model.VehicleType = tempElement.Value != "" & tempElement.Value != null ? "Tipper" : "Haulage"; objList.Add(new CHASSIS_SRCH_Model() { VehRegNo = model.VehRegNo, ChassisNo = model.ChassisNo, VehicleType = model.VehicleType }); // model.VehicleNumberPlate = tempElement.Value;//Chassis Number } } } } } catch (Exception Ex) { objList.Add(new CHASSIS_SRCH_Model() { Status = "0" }); // objList.Status = "0"; //objModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository getChassisBysuggestion" + APIChassisSearch, Ex.Message, path, errorlogtf); return objList; } } return objList; } /* public CHASSIS_ODOMETER_Model getOdoMeterBYChassis(CHASSIS_ODOMETER_Model model) { string APIChassisSearch = string.Format(ConfigurationManager.AppSettings["EOSAPI_ODOMETER_BY_CHASSIS"].ToString(), model.TicketIdAlias, model.ChassisNo.ToUpper()); try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebRequest req = WebRequest.Create(APIChassisSearch); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString(), ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString()); WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); model.ChassisNo = tempElement.Value; tempElement = doc.Descendants(ab + "Pcount").FirstOrDefault(); model.OdoMeterReading = tempElement.Value; model.Status = "1"; } } return model; } catch (Exception Ex) { model.Status = "0"; //objModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository getOdoMeterBYChassis" + APIChassisSearch, Ex.Message, path, errorlogtf); return model; } }*/ public CHASSIS_ODOMETER_Model getOdoMeterBYChassis(CHASSIS_ODOMETER_Model model) { string APIChassisSearch = string.Format(ConfigurationManager.AppSettings["EOSAPI_ODOMETER_BY_CHASSIS"].ToString(), model.TicketIdAlias, model.ChassisNo.ToUpper()); try { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebRequest req = WebRequest.Create(APIChassisSearch); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString(), ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString()); WebResponse webRes = req.GetResponse(); TicketRepository objTicketRepository = new TicketRepository(_connStr); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(resp.StatusCode.ToString(), APIChassisSearch.ToString()); objLog.ErrorLogFile(APIChassisSearch, resp.StatusCode.ToString(), path, errorlogtf); } else { if (resp.StatusCode.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(resp.StatusCode.ToString(), APIChassisSearch.ToString()); objLog.ErrorLogFile(APIChassisSearch, resp.StatusCode.ToString(), path, errorlogtf); } else { if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", APIChassisSearch.ToString()); objLog.ErrorLogFile(APIChassisSearch, "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else if (resp.StatusCode == System.Net.HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); model.ChassisNo = tempElement.Value; tempElement = doc.Descendants(ab + "Pcount").FirstOrDefault(); model.OdoMeterReading = tempElement.Value; model.Status = "1"; } } } } return model; } catch (Exception Ex) { model.Status = "0"; //objModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository getOdoMeterBYChassis" + APIChassisSearch, Ex.Message, path, errorlogtf); return model; } } /* public CHASSIS_ODOMETER_Model getCSRFToken() { CHASSIS_ODOMETER_Model objModel = new CHASSIS_ODOMETER_Model(); string APIInsertOdoMeter = ConfigurationManager.AppSettings["InsertOdometerINEOS"].ToString(); try { string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); var client = new RestClient(ConfigurationManager.AppSettings["InsertOdometerINEOS"].ToString()); client.Timeout = -1; var request = new RestRequest(Method.GET); request.AddHeader("X-CSRF-Token", "fetch"); request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword))); IRestResponse response = client.Execute(request); objModel.CSRF_Token = response.Headers.ToList().Find(x => x.Name == "x-csrf-token").Value.ToString(); var cookiesNameList = new List(); var cookiesValList = new List(); objLog.AddLogFile("CSRFToken", response.ToString(), path, errorlogtf); objLog.AddLogFile("CSRFToken", objModel.CSRF_Token, path, errorlogtf); for (var counter = 0; counter < response.Cookies.Count; counter++) { cookiesNameList.Add(response.Cookies[counter].Name.ToString()); cookiesValList.Add(response.Cookies[counter].Value.ToString()); } objModel.CookiesName = cookiesNameList.ToArray(); objModel.CookiesValues = cookiesValList.ToArray(); objLog.AddLogFile("CookiesName", objModel.CookiesName.ToString(), path, errorlogtf); objLog.AddLogFile("CookiesValues", objModel.CookiesValues.ToString(), path, errorlogtf); return objModel; } catch (Exception Ex) { objModel.Status = "5"; objModel.Message = Ex.Message; objLog.ErrorLogFile("getCSRFToken" + APIInsertOdoMeter, Ex.Message, path, errorlogtf); return objModel; } }*/ public CHASSIS_ODOMETER_Model getCSRFToken() { CHASSIS_ODOMETER_Model objModel = new CHASSIS_ODOMETER_Model(); TicketRepository objTicketRepository = new TicketRepository(_connStr); string APIInsertOdoMeter = ConfigurationManager.AppSettings["InsertOdometerINEOS"].ToString(); try { string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); var client = new RestClient(ConfigurationManager.AppSettings["InsertOdometerINEOS"].ToString()); client.Timeout = -1; var request = new RestRequest(Method.GET); request.AddHeader("X-CSRF-Token", "fetch"); request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword))); IRestResponse response = client.Execute(request); if (response.ResponseStatus.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(response.ErrorMessage.ToString(), client.BaseUrl.ToString()); objLog.ErrorLogFile(client.BaseUrl.ToString(), response.ErrorMessage.ToString(), path, errorlogtf); } else { if (response.ResponseStatus.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(response.ErrorMessage.ToString(), client.BaseUrl.ToString()); objLog.ErrorLogFile(client.BaseUrl.ToString(), response.ErrorMessage.ToString(), path, errorlogtf); } else { if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed. The server response is Unauthorized. ", client.BaseUrl.ToString()); objLog.ErrorLogFile(client.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else { objModel.CSRF_Token = response.Headers.ToList().Find(x => x.Name == "x-csrf-token").Value.ToString(); var cookiesNameList = new List(); var cookiesValList = new List(); objLog.AddLogFile("CSRFToken", response.ToString(), path, errorlogtf); objLog.AddLogFile("CSRFToken", objModel.CSRF_Token, path, errorlogtf); for (var counter = 0; counter < response.Cookies.Count; counter++) { cookiesNameList.Add(response.Cookies[counter].Name.ToString()); cookiesValList.Add(response.Cookies[counter].Value.ToString()); } objModel.CookiesName = cookiesNameList.ToArray(); objModel.CookiesValues = cookiesValList.ToArray(); objLog.AddLogFile("CookiesName", objModel.CookiesName.ToString(), path, errorlogtf); objLog.AddLogFile("CookiesValues", objModel.CookiesValues.ToString(), path, errorlogtf); } } } //new code added complete return objModel; } catch (Exception Ex) { objModel.Status = "5"; objModel.Message = Ex.Message; objLog.ErrorLogFile("getCSRFToken" + APIInsertOdoMeter, Ex.Message, path, errorlogtf); return objModel; } } /* public CHASSIS_ODOMETER_Model InsertOdoMeterInEOSAPI(string ticketId, string chassisNo, string odometer, string unit) { CHASSIS_ODOMETER_Model objModel = new CHASSIS_ODOMETER_Model(); CHASSIS_ODOMETER_Model tokenData = getCSRFToken(); try { if (tokenData.CSRF_Token != null) { CHASSIS_ODOMETER_Model objJobCardInsert = new CHASSIS_ODOMETER_Model(); string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); var client = new RestClient(ConfigurationManager.AppSettings["InsertOdometerINEOS"].ToString()); client.Timeout = -1; var request = new RestRequest(Method.POST); for (var counter = 0; counter < tokenData.CookiesName.Length; counter++) { request.AddParameter(tokenData.CookiesName[counter], tokenData.CookiesValues[counter], ParameterType.Cookie); } /// request.AddParameter("sap-usercontext", tokenData.CookieVal1, ParameterType.Cookie); // request.AddParameter("MYSAPSSO2", tokenData.CookieVal2, ParameterType.Cookie); // request.AddParameter("sap-XSRF_GWP_100", tokenData.CookieVal3, ParameterType.Cookie); // request.AddCookie( request.AddHeader("X-CSRF-Token", tokenData.CSRF_Token); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword))); // request.AddParameter("application/json", "{\"d\" : {\"TicketId\" : \"NL1119000983\",\"Vhvin\" : \"17EC30290775\",\"Mileage\" : \"9000330\",\"MileageUom1\" : \"KM\",\"Ztipper\" : \"\",\"MileageUom2\" : \"\"}}", ParameterType.RequestBody); request.AddParameter("application/json", "{\"d\" : {\"TicketId\" : \"" + ticketId + "\",\"Vhvin\" : \"" + chassisNo + "\",\"Mileage\" : \"" + odometer + "\",\"MileageUom1\" : \"" + unit + "\",\"Ztipper\" : \"\",\"MileageUom2\" : \"\"}}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); string res = response.Content; if (response.StatusCode == HttpStatusCode.Created) { objJobCardInsert = new JsonDeserializer().Deserialize(response); List tempModel = objJobCardInsert.d; if (tempModel[0].Status == "Failed") { string tempStatus = "Success"; string tempMessage = tempModel[0].Message; if (tempStatus == "Success") { objModel.Status = "1"; objModel.Message = tempMessage; } else if (tempStatus == "Failed") { objModel.Status = "9"; objModel.Message = tempMessage; } else { objLog.AddLogFile("InsertOdoMeterInEOSAPI 815", "Do not update in db " + objModel.Status, path, errorlogtf); objModel.Status = "5"; objModel.Message = tempMessage; } } else { string tempStatus = tempModel[0].Status; string tempMessage = tempModel[0].Message; if (tempStatus == "Success") { objModel.Status = "1"; objModel.Message = tempMessage; } else if (tempStatus == "Failed") { objModel.Status = "9"; objModel.Message = tempMessage; } else { objLog.AddLogFile("InsertOdoMeterInEOSAPI 839", "Do not update in db " + objModel.Status, path, errorlogtf); objModel.Status = "5"; objModel.Message = tempMessage; } } } else { objModel.Status = "5"; //objModel.Message = tempMessage; } } // no csrf token send error msg else { objModel.Status = "5"; objModel.Message = "CSRF token validation failed."; return objModel; } } catch (Exception Ex) { objModel.Status = "5"; objModel.Message = Ex.Message; objLog.ErrorLogFile("InsertOdoMeterInEOSAPI CSRF token", Ex.Message, path, errorlogtf); return objModel; } return objModel; }*/ public CHASSIS_ODOMETER_Model InsertOdoMeterInEOSAPI(string ticketId, string chassisNo, string odometer, string unit) { CHASSIS_ODOMETER_Model objModel = new CHASSIS_ODOMETER_Model(); CHASSIS_ODOMETER_Model tokenData = getCSRFToken(); try { if (tokenData.CSRF_Token != null) { CHASSIS_ODOMETER_Model objJobCardInsert = new CHASSIS_ODOMETER_Model(); string userNameAndPassword = ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_USERNAME"].ToString() + ":" + ConfigurationManager.AppSettings["EOSAPI_CHASSIS_SEARCH_PWD"].ToString(); var client = new RestClient(ConfigurationManager.AppSettings["InsertOdometerINEOS"].ToString()); client.Timeout = -1; var request = new RestRequest(Method.POST); for (var counter = 0; counter < tokenData.CookiesName.Length; counter++) { request.AddParameter(tokenData.CookiesName[counter], tokenData.CookiesValues[counter], ParameterType.Cookie); } /// request.AddParameter("sap-usercontext", tokenData.CookieVal1, ParameterType.Cookie); // request.AddParameter("MYSAPSSO2", tokenData.CookieVal2, ParameterType.Cookie); // request.AddParameter("sap-XSRF_GWP_100", tokenData.CookieVal3, ParameterType.Cookie); // request.AddCookie( request.AddHeader("X-CSRF-Token", tokenData.CSRF_Token); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword))); // request.AddParameter("application/json", "{\"d\" : {\"TicketId\" : \"NL1119000983\",\"Vhvin\" : \"17EC30290775\",\"Mileage\" : \"9000330\",\"MileageUom1\" : \"KM\",\"Ztipper\" : \"\",\"MileageUom2\" : \"\"}}", ParameterType.RequestBody); request.AddParameter("application/json", "{\"d\" : {\"TicketId\" : \"" + ticketId + "\",\"Vhvin\" : \"" + chassisNo + "\",\"Mileage\" : \"" + odometer + "\",\"MileageUom1\" : \"" + unit + "\",\"Ztipper\" : \"\",\"MileageUom2\" : \"\"}}", ParameterType.RequestBody); TicketRepository objTicketRepository = new TicketRepository(_connStr); IRestResponse response = client.Execute(request); string res = response.Content; if (response.ResponseStatus.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(response.ErrorMessage.ToString(), client.BaseUrl.ToString()); objLog.ErrorLogFile(client.BaseUrl.ToString(), response.ErrorMessage.ToString(), path, errorlogtf); } else { if (response.ResponseStatus.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(response.ErrorMessage.ToString(), client.BaseUrl.ToString()); objLog.ErrorLogFile(client.BaseUrl.ToString(), response.ErrorMessage.ToString(), path, errorlogtf); } else { if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed. The server response is Unauthorized. ", client.BaseUrl.ToString()); objLog.ErrorLogFile(client.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else { if (response.StatusCode == HttpStatusCode.Created) { objJobCardInsert = new JsonDeserializer().Deserialize(response); List tempModel = objJobCardInsert.d; if (tempModel[0].Status == "Failed") { string tempStatus = "Success"; string tempMessage = tempModel[0].Message; if (tempStatus == "Success") { objModel.Status = "1"; objModel.Message = tempMessage; } else if (tempStatus == "Failed") { objModel.Status = "9"; objModel.Message = tempMessage; } else { objLog.AddLogFile("InsertOdoMeterInEOSAPI 815", "Do not update in db " + objModel.Status, path, errorlogtf); objModel.Status = "5"; objModel.Message = tempMessage; } } else { string tempStatus = tempModel[0].Status; string tempMessage = tempModel[0].Message; if (tempStatus == "Success") { objModel.Status = "1"; objModel.Message = tempMessage; } else if (tempStatus == "Failed") { objModel.Status = "9"; objModel.Message = tempMessage; } else { objLog.AddLogFile("InsertOdoMeterInEOSAPI 839", "Do not update in db " + objModel.Status, path, errorlogtf); objModel.Status = "5"; objModel.Message = tempMessage; } } } else { objModel.Status = "5"; //objModel.Message = tempMessage; } } } } } // no csrf token send error msg else { objModel.Status = "5"; objModel.Message = "CSRF token validation failed."; return objModel; } } catch (Exception Ex) { objModel.Status = "5"; objModel.Message = Ex.Message; objLog.ErrorLogFile("InsertOdoMeterInEOSAPI CSRF token", Ex.Message, path, errorlogtf); return objModel; } return objModel; } /// /// To insert new vehicle type /// /// vehicle type details /// status 1 if record saved successfully status 2 if record already exist and status 0 if token value is wrong public VehicleTypeModel InsertNewVehicleType(VehicleTypeModel model) { VehicleTypeModel objModel = new VehicleTypeModel(); objModel.Status = "2"; try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[7]; nSqlParam[0] = new NpgsqlParameter("_id ", model.VehicleTypeId == null ? null : model.VehicleTypeId.ToUpper().Trim()); nSqlParam[1] = new NpgsqlParameter("_name ", model.VehicleTypeName == null ? null : model.VehicleTypeName.ToUpper().Trim()); nSqlParam[2] = new NpgsqlParameter("_tagging ", model.VehicleTypeTagging == null ? null : model.VehicleTypeTagging.ToUpper().Trim()); nSqlParam[3] = new NpgsqlParameter("inaction ", model.Operation == null ? null : model.Operation.ToUpper().Trim()); nSqlParam[4] = new NpgsqlParameter("inis_deleted ", model.IsDeleted); nSqlParam[5] = new NpgsqlParameter("inudanVehicleProductName", model.udanVehicleProductName); nSqlParam[6] = new NpgsqlParameter("inudanVehicleProductId", model.udanVehicleProductId); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_insert_vehicl_type"], nSqlParam); // For Telematics Use // NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_sync_customer_vehicle_model_details"]); if (ds.Tables[0].Rows[0]["sp_insert_vehicl_type"].ToString() == "1") { objModel.Status = ds.Tables[0].Rows[0]["sp_insert_vehicl_type"].ToString(); objModel.Message = "Saved Successfully"; } else { objModel.Status = ds.Tables[0].Rows[0]["sp_insert_vehicl_type"].ToString(); objModel.Message = "Model Already Exist And Udan Vehicle Parameter is upadted"; } } else { objModel.Status = "0"; objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); } return objModel; } catch (Exception Ex) { objModel.Status = "0"; objModel.Message = Ex.Message; objLog.ErrorLogFile("InsertNewVehicleType", Ex.Message, path, errorlogtf); return objModel; } } /// /// GCM model properties. /// public class GcmModel { /// /// Get or Set /// public string TicketId { get; set; } /// /// Get or Set /// public string NotificationCode { get; set; } /// /// Get or Set /// public string NotificationMessage { get; set; } } /// /// To get Notification send by GCM /// /// request detail /// GCM message info /// /// To get Notification send by GCM /// /// request detail /// GCM message info /// /// new public SendNotificationModel GcmSendNotificationNew(SendNotificationModel model) { SendNotificationModel objModel = new SendNotificationModel(); GcmModel objGcmModel = new GcmModel(); try { if (System.Configuration.ConfigurationManager.AppSettings["issendnotifiation"] != "true") { objGcmModel.TicketId = model.TicketId; objGcmModel.NotificationMessage = model.NotificationMessage; objGcmModel.NotificationCode = model.NotificationCode; objModel.Status = "1"; JavaScriptSerializer serializer = new JavaScriptSerializer(); string output = serializer.Serialize(objGcmModel); var firebaseHelper = new FirebaseNotificationSender(); string accessToken = firebaseHelper.GetAccessTokenValue(); FCMNotification objFCMNotification = new FCMNotification(); // bool issend = objFCMNotification.SendFCMNotification(model.DeviceGcmId, (ConfigurationManager.AppSettings["ProjectId"]), accessToken, model.TicketId); // string strstatus = getcurrentPreviousStatus(model.TicketId); // string[] arrStatus = strstatus.ToString().Split(','); string current_status = model.TicketStatus; string previous_status = model.PrevTicketStatus; if (model.TicketStatus == "2" && model.PrevTicketStatus == "1") { string show_message = "false"; string display_message = model.NotificationMessage; string message_tag = "Assignment"; string title = model.title;// "🚨 {0} New EOS Ticket🚨 -"; bool issend = objFCMNotification.SendFCMNotificationWithMessage(model.DeviceGcmId, (ConfigurationManager.AppSettings["ProjectId"]), accessToken, model.TicketId, current_status, previous_status, show_message, display_message, message_tag, title); } else { string show_message = "false"; string display_message = ""; string message_tag = ""; bool issend = objFCMNotification.SendFCMNotificationWithMessage(model.DeviceGcmId, (ConfigurationManager.AppSettings["ProjectId"]), accessToken, model.TicketId, current_status, previous_status, show_message, display_message, message_tag,""); } // Task strautorefresh1 = objFCMNotification.SendFCMNotification2(accessToken); // string str = strautorefresh1.Result; } } catch (Exception Ex) { if (Ex.Message == "The remote server returned an error: (301) Moved Permanently Redirect.") { objLog.ErrorLogFile("GlobalRepository GcmSendNotification1", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } else if (Ex.Message == "The remote server returned an error: (401) Unauthorized.") { objLog.ErrorLogFile("GlobalRepository GcmSendNotification2", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } else if (Ex.Message == "The remote server returned an error: (404) Not Found.") { objLog.ErrorLogFile("GlobalRepository GcmSendNotification3", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } else { objLog.ErrorLogFile("GlobalRepository GcmSendNotification4", Ex.Message, path, errorlogtf); objModel.Status = "6"; return objModel; } //throw Ex; } return objModel; } ///// old /* public SendNotificationModel GcmSendNotification(SendNotificationModel model) { SendNotificationModel objModel = new SendNotificationModel(); GcmModel objGcmModel = new GcmModel(); try { if (System.Configuration.ConfigurationManager.AppSettings["issendnotifiation"] != "true") { objGcmModel.TicketId = model.TicketId; objGcmModel.NotificationMessage = model.NotificationMessage; objGcmModel.NotificationCode = model.NotificationCode; objModel.Status = "1"; JavaScriptSerializer serializer = new JavaScriptSerializer(); string output = serializer.Serialize(objGcmModel); model.GoogleAppID = ConfigurationManager.AppSettings["GoogleAppId"]; model.SenderId = ConfigurationManager.AppSettings["SenderId"]; var value = model.NotificationMessage; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebRequest tRequest; tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(string.Format("Authorization: key={0}", model.GoogleAppID)); tRequest.Headers.Add(string.Format("Sender: id={0}", model.SenderId)); string postData = "collapse_key=score_update&time_to_live=108& delay_while_idle=1&data.message=" + output + "&data.time=" + System.DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) + "®istration_id=" + model.DeviceGcmId + ""; Console.WriteLine(postData); Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); String sResponseFromServer = tReader.ReadToEnd(); objModel.SenderId = sResponseFromServer; tReader.Close(); dataStream.Close(); tResponse.Close(); return objModel; } } catch (Exception Ex) { if (Ex.Message == "The remote server returned an error: (301) Moved Permanently Redirect.") { objLog.ErrorLogFile("GlobalRepository GcmSendNotification5", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } if (Ex.Message == "The remote server returned an error: (401) Unauthorized.") { objLog.ErrorLogFile("GlobalRepository GcmSendNotification6", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } if (Ex.Message == "The remote server returned an error: (404) Not Found.") { objLog.ErrorLogFile("GlobalRepository GcmSendNotification7", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } else { objLog.ErrorLogFile("GlobalRepository GcmSendNotification8", Ex.Message, path, errorlogtf); objModel.Status = "6"; return objModel; } //throw Ex; } return objModel; }*/ public SendNotificationModel GcmSendNotification(SendNotificationModel model) { SendNotificationModel objModel = new SendNotificationModel(); GcmModel objGcmModel = new GcmModel(); TicketRepository objTicketRepository = new TicketRepository(_connStr); try { if (System.Configuration.ConfigurationManager.AppSettings["issendnotifiation"] != "true") { objGcmModel.TicketId = model.TicketId; objGcmModel.NotificationMessage = model.NotificationMessage; objGcmModel.NotificationCode = model.NotificationCode; objModel.Status = "1"; JavaScriptSerializer serializer = new JavaScriptSerializer(); string output = serializer.Serialize(objGcmModel); model.GoogleAppID = ConfigurationManager.AppSettings["GoogleAppId"]; model.SenderId = ConfigurationManager.AppSettings["SenderId"]; var value = model.NotificationMessage; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; WebRequest tRequest; tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(string.Format("Authorization: key={0}", model.GoogleAppID)); tRequest.Headers.Add(string.Format("Sender: id={0}", model.SenderId)); string postData = "collapse_key=score_update&time_to_live=108& delay_while_idle=1&data.message=" + output + "&data.time=" + System.DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) + "®istration_id=" + model.DeviceGcmId + ""; Console.WriteLine(postData); Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); String sResponseFromServer = tReader.ReadToEnd(); objModel.SenderId = sResponseFromServer; tReader.Close(); dataStream.Close(); tResponse.Close(); return objModel; } } catch (Exception Ex) { if (Ex.Message == "The remote server returned an error: (301) Moved Permanently Redirect.") { bool isSend = objTicketRepository.emailForError("GlobalRepository GcmSendNotification5", Ex.Message); objLog.ErrorLogFile("GlobalRepository GcmSendNotification5", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } if (Ex.Message == "The remote server returned an error: (401) Unauthorized.") { bool isSend = objTicketRepository.emailForError("GlobalRepository GcmSendNotification5", Ex.Message); objLog.ErrorLogFile("GlobalRepository GcmSendNotification6", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } if (Ex.Message == "The remote server returned an error: (404) Not Found.") { bool isSend = objTicketRepository.emailForError("GlobalRepository GcmSendNotification5", Ex.Message); objLog.ErrorLogFile("GlobalRepository GcmSendNotification7", Ex.Message, path, errorlogtf); objModel.TicketId = model.TicketId; return objModel; } else { bool isSend = objTicketRepository.emailForError("GlobalRepository GcmSendNotification5", Ex.Message); objLog.ErrorLogFile("GlobalRepository GcmSendNotification8", Ex.Message, path, errorlogtf); objModel.Status = "6"; return objModel; } //throw Ex; } return objModel; } /// /// FCM Notification. /// /// /// public SendNotificationModel FcmSendNotification(SendNotificationModel model) { //string serverKey = "myServerKey"; SendNotificationModel objModel = new SendNotificationModel(); GcmModel objGcmModel = new GcmModel(); try { // GcmModel objGcmModel = new GcmModel(); objGcmModel.TicketId = model.TicketId; objGcmModel.NotificationMessage = model.NotificationMessage; objGcmModel.NotificationCode = model.NotificationCode; objModel.Status = "1"; JavaScriptSerializer serializer = new JavaScriptSerializer(); string output = serializer.Serialize(objGcmModel); model.GoogleAppID = ConfigurationManager.AppSettings["GoogleAppIdFCM"]; model.SenderId = ConfigurationManager.AppSettings["SenderIdFCM"]; var result = "-1"; var webAddr = "https://fcm.googleapis.com/fcm/send"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json"; httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", model.GoogleAppID)); httpWebRequest.Headers.Add(string.Format("Sender: id={0}", model.SenderId)); //httpWebRequest.Headers.Add("Authorization:key=" + serverKey); httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { var payload = new { to = model.DeviceGcmId, //notification = new //{ // body = "Test", // title = "Test", //}, data = new { message = output, time = System.DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) } }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(payload); // string json = "{\"to\": \"" + regID + "notification\": {\"title\": \"New dealbody\": \"20% deal!\"},\"priority\":10}"; //registration_ids, array of strings - to, single recipient streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); objModel.SenderId = result; } return objModel; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository FCMSendNotification", Ex.Message, path, errorlogtf); objModel.Status = "6"; return objModel; } } /// /// To get Notification send by GCM /// /// request detail /// GCM message info public SendNotificationModel GcmSendNotificationForKam(SendNotificationModel model) { SendNotificationModel objModel = new SendNotificationModel(); try { GcmModel objGcmModel = new GcmModel(); objModel.Status = "1"; objGcmModel.TicketId = model.TicketId; objGcmModel.NotificationMessage = model.NotificationMessage; objGcmModel.NotificationCode = model.NotificationCode; JavaScriptSerializer serializer = new JavaScriptSerializer(); string output = serializer.Serialize(objGcmModel); model.GoogleAppID = ConfigurationManager.AppSettings["GoogleAppIdForKam"]; model.SenderId = ConfigurationManager.AppSettings["SenderIdForKam"]; var value = model.NotificationMessage; WebRequest tRequest; tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(string.Format("Authorization: key={0}", model.GoogleAppID)); tRequest.Headers.Add(string.Format("Sender: id={0}", model.SenderId)); string postData = "collapse_key=score_update&time_to_live=108& delay_while_idle=1&data.message=" + output + "&data.time=" + System.DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) + "®istration_id=" + model.DeviceGcmId + ""; Console.WriteLine(postData); Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); String sResponseFromServer = tReader.ReadToEnd(); objModel.SenderId = sResponseFromServer; tReader.Close(); dataStream.Close(); tResponse.Close(); return objModel; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GcmSendNotificationForKam", Ex.Message, path, errorlogtf); objModel.Status = "6"; return objModel; } } /// /// FCM Notification KAM /// /// /// public SendNotificationModel FcmSendNotificationForKam(SendNotificationModel model) { //string serverKey = "myServerKey"; SendNotificationModel objModel = new SendNotificationModel(); try { GcmModel objGcmModel = new GcmModel(); objModel.Status = "1"; objGcmModel.TicketId = model.TicketId; objGcmModel.NotificationMessage = model.NotificationMessage; objGcmModel.NotificationCode = model.NotificationCode; JavaScriptSerializer serializer = new JavaScriptSerializer(); string output = serializer.Serialize(objGcmModel); model.GoogleAppID = ConfigurationManager.AppSettings["GoogleAppIdForKamFCM"]; model.SenderId = ConfigurationManager.AppSettings["SenderIdForKamFCM"]; var result = "-1"; var webAddr = "https://fcm.googleapis.com/fcm/send"; // var regID = "phoneRegID"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json"; httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", model.GoogleAppID)); httpWebRequest.Headers.Add(string.Format("Sender: id={0}", model.SenderId)); //httpWebRequest.Headers.Add("Authorization:key=" + serverKey); httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { var payload = new { to = model.DeviceGcmId, //notification = new //{ // body = "Test", // title = "Test", //}, data = new { message = output, time = System.DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) } }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(payload); // string json = "{\"to\": \"" + regID + "notification\": {\"title\": \"New dealbody\": \"20% deal!\"},\"priority\":10}"; //registration_ids, array of strings - to, single recipient streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); objModel.SenderId = result; } return objModel; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository FcmSendNotificationForKam", Ex.Message, path, errorlogtf); objModel.Status = "6"; objModel.TicketId = model.TicketId; return objModel; } } /// /// To get Reasons /// /// Reasons list public List GetReason() { try { DataSet ds = new DataSet(); List objList = new List(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_reasons"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new ReasonsModel { Id = s.Field("id"), ReasonName = s.Field("reason_name"), ReasonAlias = s.Field("reason_alias"), TypeId = s.Field("type_id") }).ToList(); } return objList; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetReason", Ex.Message, path, errorlogtf); throw Ex; } } /// /// To get Estimate Cost list /// /// Estimate Cost list public List GetEstimateCost() { try { DataSet ds = new DataSet(); List objList = new List(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_estimate_cost"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new EstimateCostModel { Id = s.Field("id"), CostRange = s.Field("_cost_range") }).ToList(); } return objList; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetEstimateCost", Ex.Message, path, errorlogtf); throw Ex; } } /// /// To get state list /// /// state info /// state list public List GetStateListIdWise(StateModel model) { List objList = new List(); StateModel objModel = new StateModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_state"]); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new StateModel { StateId = s.Field("state_id"), StateAlias = s.Field("state_alias") }).ToList(); } // check model has state id then return id specific details if (model.StateIdParam != null) { objList = objList.Where(s => s.StateId.ToUpper().Trim().Contains(model.StateIdParam.ToUpper().Trim())).ToList(); } // if state id is null then return all state details. if (model.StateIdParam == null) { objList = objList.Select(s => s).ToList(); } objList = objList.GroupBy(d => d.StateId).Select(d => d.FirstOrDefault()).ToList(); } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetStateListIdWise", Ex.Message, path, errorlogtf); return objList; } } /// /// this fun use for get city list state wise. /// /// pass city model as parameter /// list of city public List GetCityListStateIdWise(CityModel model) { List objList = new List(); CityModel objModel = new CityModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("instate_id ", model.StateId); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_city_state_wise"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new CityModel { CityId = s.Field("city_id"), CityName = s.Field("city_alias") }).ToList(); objList = objList.GroupBy(d => d.CityId).Select(d => d.FirstOrDefault()).ToList(); } } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAllCityListStateIdWise", Ex.Message, path, errorlogtf); return objList; } } /// /// To get dealer city state wise. /// /// van info /// dealer city state wise public List GetDealerStateCityWise(VanModel model) { DealerModel objDealerModel = new DealerModel(); List objListDealerModel = new List(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { ServiceEngineerRepository objServiceRepository = new ServiceEngineerRepository(ConfigurationManager.ConnectionStrings["Vecv_GoData"].ToString()); DataSet dsUser = new DataSet(); // dsUser = objServiceRepository.GetVanDetailUserIdWise(model); dsUser = objServiceRepository.GetVanDetailUserIdWiseOnlyDealer(model); objListDealerModel = dsUser.Tables[0].AsEnumerable().Select(s => new DealerModel { DealerId = s.Field("dealer_id"), DealerOrganizationId = s.Field("dealer_organization_id"), DealerDealerName = s.Field("dealer_dealer_name"), DealerCity = s.Field("dealer_city"), DealerState = s.Field("dealer_state"), DealerDealerDefaultLattitude = s.Field("dealer_dealer_default_lattitude"), DealerDealerDefaultLongitude = s.Field("dealer_dealer_default_longitude"), DealerContactNo = s.Field("dealer_contact_number1"), IsDeleted = s.Field("dealer_isdeleted"), Status = "1" }).ToList(); objListDealerModel = objListDealerModel.GroupBy(d => d.DealerId).Select(d => d.FirstOrDefault()).ToList(); // filter dealer state and city wise from list. if (model.DealerCityParam != null && model.DealerStateParam != null) { objListDealerModel = objListDealerModel.Where(s => s.DealerCity.ToUpper().Trim().Contains(model.DealerCityParam.ToUpper().Trim()) && s.DealerState.ToUpper().Trim().Contains(model.DealerStateParam.ToUpper().Trim()) ).ToList(); } // return all dealer. if (model.DealerCityParam == null && model.DealerStateParam == null) { objListDealerModel = objListDealerModel.Select(s => s).ToList(); } // filter dealer city wise from list. if (model.DealerCityParam != null && model.DealerStateParam == null) { //objListDealerModel = objListDealerModel.Where(s => s.DealerCity.ToUpper().Trim().Contains(model.DealerCityParam.ToUpper().Trim())).ToList(); } // filter dealer state wise from list. if (model.DealerCityParam == null && model.DealerStateParam != null) { objListDealerModel = objListDealerModel.Where(s => s.DealerState.ToUpper().Trim().Contains(model.DealerStateParam.ToUpper().Trim())).ToList(); } objDealerModel.Status = "1"; } else { objDealerModel.Status = "0"; objDealerModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); return objListDealerModel; } List objListDealerModel1 = new List(); objListDealerModel1 = objListDealerModel.OrderBy(r => r.DealerDealerName).ToList(); return objListDealerModel1; } catch (Exception Ex) { objDealerModel.Status = "0"; objDealerModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository GetDealerStateCityWise", Ex.Message, path, errorlogtf); return objListDealerModel; } } /// /// To get dealer city state wise. /// /// van info /// dealer city state wise public List GetDealerStateCityWiseFuelType(VanModel model) { DealerModel objDealerModel = new DealerModel(); List objListDealerModel = new List(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { ServiceEngineerRepository objServiceRepository = new ServiceEngineerRepository(ConfigurationManager.ConnectionStrings["Vecv_GoData"].ToString()); DataSet dsUser = new DataSet(); // dsUser = objServiceRepository.GetVanDetailUserIdWise(model); dsUser = objServiceRepository.GetVanDetailUserIdWiseOnlyDealerFuelType(model); objListDealerModel = dsUser.Tables[0].AsEnumerable().Select(s => new DealerModel { DealerId = s.Field("dealer_id"), DealerOrganizationId = s.Field("dealer_organization_id"), DealerDealerName = s.Field("dealer_dealer_name"), DealerCity = s.Field("dealer_city"), DealerState = s.Field("dealer_state"), DealerDealerDefaultLattitude = s.Field("dealer_dealer_default_lattitude"), DealerDealerDefaultLongitude = s.Field("dealer_dealer_default_longitude"), DealerContactNo = s.Field("dealer_contact_number1"), IsDeleted = s.Field("dealer_isdeleted"), FuelType = s.Field("_fuel_type"), Status = "1" }).ToList(); objListDealerModel = objListDealerModel.GroupBy(d => d.DealerId).Select(d => d.FirstOrDefault()).ToList(); // filter dealer state and city wise from list. if (model.DealerCityParam != null && model.DealerStateParam != null) { objListDealerModel = objListDealerModel.Where(s => s.DealerCity.ToUpper().Trim().Contains(model.DealerCityParam.ToUpper().Trim()) && s.DealerState.ToUpper().Trim().Contains(model.DealerStateParam.ToUpper().Trim()) ).ToList(); } // return all dealer. if (model.DealerCityParam == null && model.DealerStateParam == null) { objListDealerModel = objListDealerModel.Select(s => s).ToList(); } // filter dealer city wise from list. if (model.DealerCityParam != null && model.DealerStateParam == null) { //objListDealerModel = objListDealerModel.Where(s => s.DealerCity.ToUpper().Trim().Contains(model.DealerCityParam.ToUpper().Trim())).ToList(); } // filter dealer state wise from list. if (model.DealerCityParam == null && model.DealerStateParam != null) { objListDealerModel = objListDealerModel.Where(s => s.DealerState.ToUpper().Trim().Contains(model.DealerStateParam.ToUpper().Trim())).ToList(); } objDealerModel.Status = "1"; } else { objDealerModel.Status = "0"; objDealerModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); return objListDealerModel; } List objListDealerModel1 = new List(); objListDealerModel1 = objListDealerModel.OrderBy(r => r.DealerDealerName).ToList(); return objListDealerModel1; } catch (Exception Ex) { objDealerModel.Status = "0"; objDealerModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository GetDealerStateCityWise", Ex.Message, path, errorlogtf); return objListDealerModel; } } /// /// To get all sla time. /// /// sla info /// list of sla public List GetSla(SlaModel model) { SlaModel objSlaModel = new SlaModel(); List objListSlaModel = new List(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_sla_for_van_position"]); objListSlaModel = ds.Tables[0].AsEnumerable().Select(s => new SlaModel { Id = s.Field("id"), SlaTime = s.Field("sla_time"), Status = "1" }).ToList(); objSlaModel.Status = "1"; } else { objSlaModel.Status = "0"; objSlaModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); return objListSlaModel; } return objListSlaModel; } catch (Exception Ex) { objSlaModel.Status = "0"; objSlaModel.Message = Ex.Message; objLog.ErrorLogFile("GlobalRepository GetSla", Ex.Message, path, errorlogtf); return objListSlaModel; } } /// /// To create data logs. /// /// pass event as parameter(which method call) /// pass model /// start date of event /// end date of a event(method) public void AddLogFile(string event_, object model, string startDate, string endDate) { try { if (ConfigurationManager.AppSettings["Log"] == "true") { string data = ""; if (model != null) { Type type = model.GetType(); PropertyInfo[] properties = type.GetProperties(); // read property name and data from models. foreach (PropertyInfo property in properties) { data = data + (property.Name + ':' + property.GetValue(model, null) + Environment.NewLine); } } else { data = " model is null "; } string path = HttpContext.Current.Server.MapPath("~/Log/");//get path of file location string filename = "Log_" + DateTime.Now.ToString(ConfigurationManager.AppSettings["DateFormat"]) + ".txt";// create file date wise. string filepath = path + filename; if (File.Exists(filepath)) { using (StreamWriter writer = new StreamWriter(filepath, true)) { if (startDate != null) { //write content in log file. writer.WriteLine("-------------------" + event_ + " START " + startDate + "-------------"); writer.WriteLine(data + Environment.NewLine + "Function Exe Start Time :" + DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"])); } if (endDate != null) { writer.WriteLine("-------------------" + event_ + " END " + endDate + "-------------" + Environment.NewLine); } writer.Close(); } } else { // create file if not exists and write content in log file. StreamWriter writer = File.CreateText(filepath); if (startDate != null) { writer.WriteLine("-------------------" + event_ + " START " + startDate + "-------------"); writer.WriteLine(data + Environment.NewLine + "Function Exe Start Time :" + DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"])); } if (endDate != null) { writer.WriteLine("-------------------" + event_ + " END " + endDate + "-------------" + Environment.NewLine); } writer.Close(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository AddLogFile", Ex.Message, path, errorlogtf); throw Ex; } } /// /// To create error logs. /// /// pass event name as parameter(which method call) /// error text public void ErrorLogFile(string event_, string msg) { try { if (ConfigurationManager.AppSettings["ErrorLog"] == "true") { string path = HttpContext.Current.Server.MapPath("~/Log/"); string filename = "Error_Log_" + DateTime.Now.ToString(ConfigurationManager.AppSettings["DateFormat"]) + ".txt"; string filepath = path + filename; if (File.Exists(filepath)) { using (StreamWriter writer = new StreamWriter(filepath, true)) { writer.WriteLine(Environment.NewLine + "-------------------" + event_ + " : " + DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) + "--------------" + Environment.NewLine + "Error_message :" + msg + Environment.NewLine); writer.Close(); } } else { StreamWriter writer = File.CreateText(filepath); writer.WriteLine(Environment.NewLine + "------------------" + event_ + " : " + DateTime.Now.ToString(ConfigurationManager.AppSettings["DateTimeFormat"]) + "--------------" + Environment.NewLine + "Error_message :" + msg + Environment.NewLine); writer.Close(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository ErrorLogFile", Ex.Message, path, errorlogtf); throw Ex; } } /// /// To insert or update reasons. /// /// reason info /// status public ReasonsModel UpdateOrInsertReason(ReasonsModel model) { ReasonsModel objModel = new ReasonsModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[5]; nSqlParam[0] = new NpgsqlParameter("inid ", model.Id);// if id is null then go for insert else update. nSqlParam[1] = new NpgsqlParameter("inreason_name ", model.ReasonName); nSqlParam[2] = new NpgsqlParameter("inreason_alias ", model.ReasonAlias); nSqlParam[3] = new NpgsqlParameter("intype_id ", model.TypeId); nSqlParam[4] = new NpgsqlParameter("inis_deleted ", model.IsDeleted); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_insert_or_update_resaons"], nSqlParam); // For Telematics Use // NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_sync_dropdown_options"]); if (ds.Tables[0].Rows[0]["sp_insert_or_update_resaons"].ToString() == "1") { objModel.Status = "1"; objModel.Message = "Record Added Succesfully"; } else if (ds.Tables[0].Rows[0]["sp_insert_or_update_resaons"].ToString() == "2") { objModel.Status = "2"; objModel.Message = "Record Already Exist"; } } else { objModel.Status = "0"; objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); } return objModel; } catch (Exception Ex) { objModel.Status = "0"; objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objLog.ErrorLogFile("GlobalRepository UpdateOrInsertReason", Ex.Message, path, errorlogtf); return objModel; } } /// /// To get language list /// /// lanuage info /// language list public List GetLanguageList(LanguageModel model) { List objList = new List(); try { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inid", model == null ? null : model.Id); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_languages"], nSqlParam); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new LanguageModel { Id = s.Field("_id"), LanguageAlias = s.Field("_languages_alias"), LanguageName = s.Field("_language_name"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetLanguageList", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Toll free No Sources list /// /// Toll free No Sources list public List GetTollFreeNoSources() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_toll_free_no_source"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetTollFreeNoSources", Ex.Message, path, errorlogtf); } return objList; } public List GetNatureOfProblem() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_nature_of_problem"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetNatureOfProblem", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Warranty list /// /// Warranty list public List GetWarranty() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_warranty_details"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetWarranty", Ex.Message, path, errorlogtf); } return objList; } /// /// To get drop down list /// /// drop down list public List GetDropDownList() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_dropdown_list_items_types"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetDropDownList", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Warranty list /// /// Warranty list public List GetAllReasons() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_dropdown_options"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllReasons", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Vehicle type list /// /// Vehicle type list public List GetAllVehicleType() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_vehicle_types"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllVehicleType", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Vehicle type list /// /// Vehicle type list public List GetAll24HrsClouserReason() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_24hrs_closure_reason"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAll24HrsClouserReason", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Opportunity lost reasons /// /// Opportunity lost reasons public List GetAllOpportunityLostReason() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_opportunity_loss_reason"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile(" GlobalRepository GetAllOpportunityLostReason", Ex.Message, path, errorlogtf); } return objList; } //------------------ *** added on 25-11-2020 (start) ------------------------------------------ /// /// To get Ticket closed reasons /// /// public List GetAllClosedTicketReason() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_ticket_closed_reason"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllClosedTicketReason", Ex.Message, path, errorlogtf); } return objList; } //------------------ *** added on 25-11-2020 (end) ------------------------------------------ /// /// To get Opportunity lost reasons /// /// Opportunity lost reasons public List GetAllDelayedReasonMorethan24Hrs() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_delayed_reason_for_24_hours"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllDelayedReasonMorethan24Hrs", Ex.Message, path, errorlogtf); } return objList; } /// /// To get FeedBack type list /// /// FeedBack type list public List GetAllFeedBackTypes() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_feedback_question"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllFeedBackTypes", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Suggestion list /// /// Suggestion list public List GetAllSuggestion() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_suggestions"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllSuggestion", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Complaint list /// /// Complaint list public List GetAllComplaint() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_complaints"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllComplaint", Ex.Message, path, errorlogtf); } return objList; } /// /// To get Call Status list /// /// Call Status list public List GetAllCallStatus() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_call_status"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllCallStatus", Ex.Message, path, errorlogtf); } return objList; } /// /// To get organization chart list. /// /// organization chart list public List GetOrganizationListChart() { List objList = new List(); OrgganizationModel objModel; try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_organizations"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { objModel = new OrgganizationModel(); string[] orgArray = ds.Tables[0].Rows[i]["_path"].ToString().Split('/'); List orgList = orgArray.ToList(); orgList.RemoveAll(p => string.IsNullOrEmpty(p)); orgArray = orgList.ToArray(); if (i == 0) { objModel.OrganizationName = ds.Tables[0].AsEnumerable() .Where( w => w.Field("_depth").Equals(orgArray.Count().ToString()) && w.Field("_alias").Equals(orgArray[orgArray.Count() - 1].ToString()) ) .Select(s => s.Field("_organization_name")).FirstOrDefault(); objModel.Color = ds.Tables[0].AsEnumerable() .Where( w => w.Field("_depth").Equals(orgArray.Count().ToString()) && w.Field("_alias").Equals(orgArray[orgArray.Count() - 1].ToString()) ) .Select(s => s.Field("_color")).FirstOrDefault(); objModel.Parent = null; } else { objModel.OrganizationName = ds.Tables[0].AsEnumerable() .Where( w => w.Field("_depth").Equals(orgArray.Count().ToString()) && w.Field("_alias").Equals(orgArray[orgArray.Count() - 1].ToString()) ) .Select(s => s.Field("_organization_name")).FirstOrDefault(); objModel.Color = ds.Tables[0].AsEnumerable() .Where( w => w.Field("_depth").Equals(orgArray.Count().ToString()) && w.Field("_alias").Equals(orgArray[orgArray.Count() - 1].ToString()) ) .Select(s => s.Field("_color")).FirstOrDefault(); objModel.Parent = ds.Tables[0].AsEnumerable() .Where( w => w.Field("_depth").Equals((orgArray.Count() - 1).ToString()) && w.Field("_alias").Equals(orgArray[orgArray.Count() - 2].ToString()) ) .Select(s => s.Field("_organization_name")).FirstOrDefault(); } objList.Add(objModel); } } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetOrganizationListChart", Ex.Message, path, errorlogtf); } return objList; } public List GetReasonForDealer() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_reason_for_assign_to_dealer"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetReasonForDealer", Ex.Message, path, errorlogtf); } return objList; } /// /// To send SMS /// /// The complete URL for SMS which consists of username, password, message to, messgae from, sms body /* public void SendMessage(string smsUrl) { try { if (System.Configuration.ConfigurationManager.AppSettings["SMSIsBlocked"] != "true") { objLog.AddLogFile("GlobalRepository SendMessage Url", smsUrl, path, errorlogtf); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(smsUrl); //request.Headers.Add("X-Mashape-Key", "kgdDYTm7FBmshs7MEi16Xlvr1mEvp12woJFjsnYbNNrLfK8qyi"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string source = sr.ReadToEnd(); sr.Close(); } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository SendMessage", Ex.Message, path, errorlogtf); } }*/ public void SendMessage(string smsUrl) { try { if (System.Configuration.ConfigurationManager.AppSettings["SMSIsBlocked"] != "true") { objLog.AddLogFile("GlobalRepository SendMessage Url", smsUrl, path, errorlogtf); TicketRepository objTicketRepository = new TicketRepository(_connStr); var clientVehicleType = new RestClient(smsUrl); var requestVehicleType = new RestRequest(Method.GET); IRestResponse responseVehicleType = clientVehicleType.Execute(requestVehicleType); if (responseVehicleType.ResponseStatus.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } { if (responseVehicleType.ResponseStatus.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.OK) { string source = responseVehicleType.Content; } } } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository SendMessage", Ex.Message, path, errorlogtf); } } /* public void SendMessageEscalation(string smsUrl) { try { if (System.Configuration.ConfigurationManager.AppSettings["isEscalationSMSSend"] != "true") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(smsUrl); //request.Headers.Add("X-Mashape-Key", "kgdDYTm7FBmshs7MEi16Xlvr1mEvp12woJFjsnYbNNrLfK8qyi"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string source = sr.ReadToEnd(); sr.Close(); } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository SendMessageEscalation", Ex.Message, path, errorlogtf); } }*/ public void SendMessageEscalation(string smsUrl) { try { if (System.Configuration.ConfigurationManager.AppSettings["isEscalationSMSSend"] != "true") { TicketRepository objTicketRepository = new TicketRepository(_connStr); var clientVehicleType = new RestClient(smsUrl); var requestVehicleType = new RestRequest(Method.GET); IRestResponse responseVehicleType = clientVehicleType.Execute(requestVehicleType); if (responseVehicleType.ResponseStatus.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.ResponseStatus.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized. ", path, errorlogtf); } else if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.OK) { string source = responseVehicleType.Content; } } } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository SendMessageEscalation", Ex.Message, path, errorlogtf); } } public List GetAppVersion(AppModel model) { List objList = new List(); AppModel objModel = new AppModel(); try { objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inapp_code ", model.AppCode); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_app_config_details"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new AppModel { AppCode = s.Field("_app_code"), AppVersion = s.Field("_app_version"), AppName = s.Field("_app_name"), ModifiedDate = s.Field("_last_modified_date") }).ToList(); } } else { objModel.Message = ConfigurationManager.AppSettings["DeviceConfigurationTokenMessage"].ToString(); objList.Add(objModel); } return objList; } catch (Exception Ex) { objModel.Message = ConfigurationManager.AppSettings["PwdErrorMsg"].ToString() + Ex.Message; objList.Add(objModel); objLog.ErrorLogFile("GlobalRepository GetAppVersion", Ex.Message, path, errorlogtf); return objList; } } /// /// To get Customer Not Satisfied Questions list /// /// Customer Not Satisfied Questions list public List GetAllCustomerNotSatisfiedQuestions() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_not_satisfied_questions"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllCustomerNotSatisfiedQuestions", Ex.Message, path, errorlogtf); } return objList; } /// /// To get customer FeedBack type list /// /// FeedBack type list public List GetAllCustomerFeedBackTypes() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_feedback_question"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetAllCustomerFeedBackTypes", Ex.Message, path, errorlogtf); } return objList; } public List GetFeedBackReasonList() { List objList = new List(); try { DataSet ds = new DataSet(); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_feedback_reason_list"]); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new TollFreeNoSourceModel { Id = s.Field("id"), ReasonAlias = s.Field("reason_alias"), ReasonName = s.Field("reason_name"), TypeAlias = s.Field("type_alias"), TypeId = s.Field("type_id"), }).ToList(); } } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository GetFeedBackReasonList", Ex.Message, path, errorlogtf); } return objList; } #endregion //added on 26-11-2020 public InsertOpenTicket checkRegistartionNoandGetVehicleDetail(InsertOpenTicket model) { try { //objCustomerVehicleModel.Status = 1; if (model.VehicleRegistrationNumber == null) { model.VehicleRegistrationNumber = ""; } if (model.ChassisNo == null) { model.ChassisNo = ""; } // model.ChassisNo = "068007"; objAuthorization = new AuthenticationRepository(); if (objAuthorization.AuthenticateDevice(model.Token)) { DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[2]; if (model.VehicleRegistrationNumber == null || model.VehicleRegistrationNumber == "") { nSqlParam[0] = new NpgsqlParameter("inregistration_number ", null); nSqlParam[1] = new NpgsqlParameter("inchassis_number ", model.ChassisNo); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_detail_By_DBM"], nSqlParam); } else { nSqlParam[0] = new NpgsqlParameter("inregistration_number ", model.VehicleRegistrationNumber); nSqlParam[1] = new NpgsqlParameter("inchassis_number ", null); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_detail_By_DBM_registration_number"], nSqlParam); } if (ds.Tables[0].Rows.Count > 0) { //tempElement = doc.Descendants(ab + "Vehicle_Warranty").FirstOrDefault(); model.vehicle_warranty = "vehicle_warranty"; //tempElement = doc.Descendants(ab + "AMC").FirstOrDefault(); model.vehicle_amc = "AMC"; //added on 12-11-2020 // tempElement = doc.Descendants(ab + "Emission_norms").FirstOrDefault(); model.vehicle_emission_norms = ds.Tables[0].Rows[0]["_vehicle_type"].ToString(); // tempElement = doc.Descendants(ab + "sales_date").FirstOrDefault(); model.vehicle_sales_date = ds.Tables[0].Rows[0]["_vehicle_sales_date"].ToString(); } } return model; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkRegistartionNoandGetVehicleDetail", Ex.Message, path, errorlogtf); return model; } } //added on 26-11-2020 public InsertOpenTicket checkKamManagerDetail(InsertOpenTicket model) { try { model.KamChampId = "111"; model.KamChampName = "qqq"; model.KamChampTel = "aa"; model.KamChampEmail = "a@b.com"; model.KamRegHId = "bb"; model.KamRegHName = "asas"; model.KamRegHTel = "aaaaa"; model.KamRegHEmail = "aaaa"; model.KamNatHId = ""; model.KamNatHName = ""; model.KamNatHTel = ""; model.KamNatHEmail = ""; return model; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkKamManagerDetail", Ex.Message, path, errorlogtf); return model; } } /* public string getvehiclewarrantychassis(string chassisno) { string vehwarrnty = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), "", chassisno); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); tempElement = doc.Descendants(ab + "Vehicle_Warranty").FirstOrDefault(); vehwarrnty = tempElement.Value; } } return vehwarrnty; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository getvehiclewarrantychassis" + APIRegistrationNo, Ex.Message, path, errorlogtf); return vehwarrnty; } }*/ public string getvehiclewarrantychassis(string chassisno) { TicketRepository objTicketRepository = new TicketRepository(_connStr); string vehwarrnty = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), "", chassisno); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); tempElement = doc.Descendants(ab + "Vehicle_Warranty").FirstOrDefault(); vehwarrnty = tempElement.Value; } } else if (resp.StatusCode == HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed: Unauthorized access", APIRegistrationNo); objLog.ErrorLogFile(APIRegistrationNo, "API Login Failed: Unauthorized access", path, errorlogtf); } return vehwarrnty; } catch (Exception Ex) { bool isSend = objTicketRepository.emailForError(APIRegistrationNo, Ex.Message); objLog.ErrorLogFile("GlobalRepository getvehiclewarrantychassis" + APIRegistrationNo, Ex.Message, path, errorlogtf); return vehwarrnty; } } /*public string getvehiclewarranty(string regNo) { string vehwarrnty = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), regNo, ""); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); tempElement = doc.Descendants(ab + "Vehicle_Warranty").FirstOrDefault(); vehwarrnty = tempElement.Value; } } return vehwarrnty; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository getvehiclewarranty" + APIRegistrationNo, Ex.Message, path, errorlogtf); return vehwarrnty; } }*/ public string getvehiclewarranty(string regNo) { TicketRepository objTicketRepository = new TicketRepository(_connStr); string vehwarrnty = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGCUSTOMERDATA"].ToString(), regNo, ""); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); tempElement = doc.Descendants(ab + "Vehicle_Warranty").FirstOrDefault(); vehwarrnty = tempElement.Value; } } else if (resp.StatusCode == HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed: Unauthorized access", APIRegistrationNo); objLog.ErrorLogFile(APIRegistrationNo, "API Login Failed: Unauthorized access", path, errorlogtf); } return vehwarrnty; } catch (Exception Ex) { bool isSend = objTicketRepository.emailForError("API Login Failed: Unauthorized access", APIRegistrationNo); objLog.ErrorLogFile("GlobalRepository getvehiclewarranty" + APIRegistrationNo, Ex.Message, path, errorlogtf); return vehwarrnty; } } /* public string getDeviceType(string chassisNo) { string devicedetails = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORDEVICETYPE"].ToString(), chassisNo, ""); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORDEVICETYPE"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORDEVICETYPE"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORDEVICETYPE"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORDEVICETYPE"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices"; // Accessing the vhvin property string vhvin = doc.Root.Element(d + "zteldevicetype")?.Value; string zimei = doc.Root.Element(d + "zimei")?.Value; devicedetails = vhvin + "," + zimei; } } return devicedetails; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository getvehiclewarranty" + APIRegistrationNo, Ex.Message, path, errorlogtf); return devicedetails; } }*/ public string getDeviceType(string chassisNo) { string devicedetails = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORDEVICETYPE"].ToString(), chassisNo, ""); var clientVehicleType = new RestClient(APIRegistrationNo); clientVehicleType.Timeout = 10000; // clientVehicleType.Timeout =-1; var requestVehicleType = new RestRequest(Method.GET); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //requestVehicleType.AddParameter("chassisno", chassisno); var username = ConfigurationManager.AppSettings["EOSUSERNAMEFORDEVICETYPE"].ToString(); var password = ConfigurationManager.AppSettings["EOSPASSWORDFORDEVICETYPE"].ToString(); // Add Basic Authentication var credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")); // Add Basic Authentication header requestVehicleType.AddHeader("Authorization", $"Basic {credentials}"); requestVehicleType.AddHeader("Accept", "application/xml"); requestVehicleType.AddHeader("Content-Type", "application/xml"); try { IRestResponse responseVehicleType = clientVehicleType.Execute(requestVehicleType); TicketRepository objTicketRepository = new TicketRepository(_connStr); if (responseVehicleType.ResponseStatus.ToString() == "Error") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.ResponseStatus.ToString() == "TimedOut") { bool isSend = objTicketRepository.emailForError(responseVehicleType.ErrorMessage.ToString(), clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), responseVehicleType.ErrorMessage.ToString(), path, errorlogtf); } else { if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", clientVehicleType.BaseUrl.ToString()); objLog.ErrorLogFile(clientVehicleType.BaseUrl.ToString(), "API Login Failed:Login failed. The server response is Unauthorized.", path, errorlogtf); } else if (responseVehicleType.StatusCode == System.Net.HttpStatusCode.OK) { byte[] bytes = Encoding.Default.GetBytes(responseVehicleType.Content); string res = Encoding.UTF8.GetString(bytes); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices"; // Accessing the vhvin property string vhvin = doc.Root.Element(d + "zteldevicetype")?.Value; string zimei = doc.Root.Element(d + "zimei")?.Value; devicedetails = vhvin + "," + zimei; } } } } return devicedetails; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository getvehiclewarranty" + APIRegistrationNo, Ex.Message, path, errorlogtf); return devicedetails; } } /* public string getvehicleExtendedwarranty(string CHASSISNO) { string vehwarrnty = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGEXTENDEDWARRANTYDATA"].ToString(), CHASSISNO.ToUpper(), ""); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; CustomerVehicleModelDBM objVeh = new CustomerVehicleModelDBM(); try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); tempElement = doc.Descendants(ab + "Current_Status").FirstOrDefault(); vehwarrnty = tempElement.Value; // objVeh.extended_warranty = vehwarrnty; tempElement = doc.Descendants(ab + "Ew_End_Date").FirstOrDefault(); //objVeh.warranty_end_date = tempElement.Value; vehwarrnty = vehwarrnty + "," + tempElement.Value; } } return vehwarrnty; } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository getvehicleExtendedwarranty" + APIRegistrationNo, Ex.Message, path, errorlogtf); return vehwarrnty; } }*/ public string getvehicleExtendedwarranty(string CHASSISNO) { TicketRepository objTicketRepository = new TicketRepository(_connStr); string vehwarrnty = ""; string APIRegistrationNo = string.Format(ConfigurationManager.AppSettings["EOSAPIFORGETTINGEXTENDEDWARRANTYDATA"].ToString(), CHASSISNO.ToUpper(), ""); WebRequest req = WebRequest.Create(APIRegistrationNo); req.Method = "GET"; string userNameAndPassword = ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString() + ":" + ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString(); req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userNameAndPassword)); req.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EOSUSERNAMEFORGETTINGCUSTOMERDATA"].ToString(), ConfigurationManager.AppSettings["EOSPASSWORDFORGETTINGCUSTOMERDATA"].ToString()); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; CustomerVehicleModelDBM objVeh = new CustomerVehicleModelDBM(); try { WebResponse webRes = req.GetResponse(); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { StreamReader ResponseDataStream = new StreamReader(resp.GetResponseStream()); String res = ResponseDataStream.ReadToEnd(); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.LoadXml(res); XmlNodeList nodeList = XMLDoc.GetElementsByTagName("content"); XNamespace ab = "http://schemas.microsoft.com/ado/2007/08/dataservices"; string Short_Fall = string.Empty; foreach (XmlNode node in nodeList) { XDocument doc = XDocument.Parse(node.InnerXml); XElement tempElement = doc.Descendants(ab + "Vhvin").FirstOrDefault(); tempElement = doc.Descendants(ab + "Current_Status").FirstOrDefault(); vehwarrnty = tempElement.Value; // objVeh.extended_warranty = vehwarrnty; tempElement = doc.Descendants(ab + "Ew_End_Date").FirstOrDefault(); //objVeh.warranty_end_date = tempElement.Value; vehwarrnty = vehwarrnty + "," + tempElement.Value; } } else if (resp.StatusCode == HttpStatusCode.Unauthorized) { bool isSend = objTicketRepository.emailForError("API Login Failed: Unauthorized access", APIRegistrationNo); objLog.ErrorLogFile(APIRegistrationNo, "API Login Failed: Unauthorized access", path, errorlogtf); } return vehwarrnty; } catch (Exception Ex) { bool isSend = objTicketRepository.emailForError("API Login Failed:Login failed.The server response is Unauthorized. ", APIRegistrationNo); objLog.ErrorLogFile("GlobalRepository getvehicleExtendedwarranty" + APIRegistrationNo, Ex.Message, path, errorlogtf); return vehwarrnty; } } public async Task getBatteryVoltage(ClodantAPIModel model) { string batteryvoltage = ""; try { string cloudantUrl = ConfigurationManager.AppSettings["CloudantId"].ToString(); string apiKey = ConfigurationManager.AppSettings["CloudantKey"].ToString(); string partitionKeyVal = model.device_id; ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => { Console.WriteLine($"SSL Policy Errors: {sslPolicyErrors}"); return sslPolicyErrors == SslPolicyErrors.None; }; var clientNew = new HttpClient(); // Set the authentication header var authHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes($"apikey-v2-{apiKey}")); clientNew.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeader); List data = new List(); DateTime now = DateTime.Now; string fullDateTime = now.ToString("yyyy-MM-dd HH:mm:ss"); DateTime dateTime = DateTime.Parse(fullDateTime); string dateOnly = dateTime.ToString("yyyy-MM-dd").Replace("-", ""); string timeOnly = dateTime.ToString("HH:mm:ss").Replace(":", ""); string timeBefore24Hours = now.AddHours(-24).ToString("yyyy-MM-dd HH:mm:ss"); DateTime dateTime1 = DateTime.Parse(timeBefore24Hours); string dateOnly1 = dateTime1.ToString("yyyy-MM-dd").Replace("-", ""); string timeOnly1 = dateTime1.ToString("HH:mm:ss").Replace(":", ""); string stime = dateOnly + timeOnly; string stime2 = dateOnly1 + timeOnly1; DateTime date = DateTime.Now; // Current date and time int currentYear = DateTime.Now.Year; string monthAbbreviation = date.ToString("MMM"); model.startdate = Convert.ToInt64(stime2); model.enddate = Convert.ToInt64(stime); // string dbName = "wperinfo_sep_2024"; string dbName = "wperinfo_" + (monthAbbreviation).ToLower() + "_" + currentYear; var queryVal = new JObject { ["selector"] = new JObject { ["eDateTime"] = new JObject { ["$gt"] = model.startdate, ["$lt"] = model.enddate }, ["type"] = model.packet_info }, }; var jsonContent = JsonConvert.SerializeObject(queryVal); var contentVal = new StringContent(jsonContent, Encoding.UTF8, "application/json"); // Send the POST request to query the database var responseVal = await clientNew.PostAsync($"{cloudantUrl}/{dbName}/_partition/{partitionKeyVal}/_find", contentVal); if (responseVal.IsSuccessStatusCode) { var resultval = await responseVal.Content.ReadAsStringAsync(); // var jsonResponse = JObject.Parse(resultval); // Deserialize JSON into Root object Root rootObject = JsonConvert.DeserializeObject(resultval); // Accessing the list of documents List documents = rootObject.docs; List orderedDocuments = documents // Ensure valid DateTime .OrderByDescending(doc => doc.eDateTime) .ToList(); Document objDocument = orderedDocuments.FirstOrDefault(); if (model.packet_info == "PER_BS4") { batteryvoltage = objDocument.ParsedValue[19]; } // var apiResponse = jsonResponse.ToObject(); Console.WriteLine("Query Result:"); Console.WriteLine(resultval); } else { Console.WriteLine($"Error: {responseVal.StatusCode}"); var errorContent = await responseVal.Content.ReadAsStringAsync(); Console.WriteLine(errorContent); } //Console.WriteLine($"Create Database Response: {createDbResponse.StatusCode}"); } catch (Exception Ex) { // write error log into file objLog.ErrorLogFile("Battery Voltage Error", Ex.Message, path, errorlogtf); } return batteryvoltage; } public async Task Autorefreshnew(string authtoken, string senderid, string deviceid, string strmessage, string ticketid, string msg) { string success = ""; try { var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/v1/projects/eicher-eos-androidx/messages:send"); request.Headers.Add("Sender", senderid); request.Headers.Add("Authorization", "Bearer " + authtoken); //request.Headers.Add("Authorization", "Bearer ya29.c.c0ASRK0GZ9QfuQxwJtj2wlPC3JR3mJL2kIFK74O-XP0j_5c8WkCtrbq5fxNo9dEtzlvGHdIoxnnnqvT_Mzb8pFSiaRu3INTBTCrgxfQaXtEeHrK4TSjc5SHfPJllTmrBHN3KZYTk-tGeAht_ZZE-u5U6fk5TtixbyE5_Y1NiJ2yLvd1RVxAFmofvnjwtLnNavH2r1zrn26sFdtqrcuJSxZ8lFBqlMYMsDBtpXg1xmYKDqEXzM6DeGKZmmdQD8ilMtaELBca83jEt74SUdLYLh2ZK3oFzXch2sYfekZaN5YSxGxQmKXqSDN_7ZNqZfo3cXvaN3FGjlETfzA9CDIvHYMM0dneXe0PFEh46gA1lzHDEi71w8YFkH6WSoL384Pl5kcS28V1mFcQghbncQgymiaai_5sJdha--itw9_Vi5a05imBBgaSd6h14V__V9IF1WZ-VW17Qb7hw89RgkB5y98R34tl9i4hS_oqMjbd6p3lrJXbrodty7o99jqWaYRMrY_fF3Z-3od79XeW5-aI1IXxBlFtdw5ldahZS9buf5ymunpSmhj5FBVfOaMXsgwIqojcFUin204IMa8q4mQndmt6uZQpfFUfSvrcm9_b-p89xwihgBqxte-Jr2kncp4eoSdwQQ-oo9oIearcJtu3gFOJZ9tZv0b31qjlxBkaiRf_OFBIfkUOQX44kkif5MjosaYkuMMXZVnovswZic09q9zgFvhOcVQXs5-YWybXM-0I5Og-chUbBfgVgJ-dM8YJs-q87-FQuxkW1qRcg-xXWkafhhUlv9nXWqrktc_l2JB_Uftq-ZZczy_y1uO6rRlRuFo3l0V_Odv-i5jghVB3fsjq2m4kMgXv4MoXzwy_oFurJB3iu3d-SmMiji_onBjO6t76-FxYJbmtZ9usSs_0ojQRQ3ZzOBwFdyJvOVBnv9RYeyzrupa9OO1ImkWJd0ByumcX53Zw021cipO01J_08mqYY3ut30usydaFYna6z9951s71mg5vxtcfdZ"); // var content = new StringContent("{\r\n \"message\": {\r\n \"token\":\"c_QqP7NPIkU:APA91bEjh1g13lX7efBqXQ5W6tEPVfi4Mv9RwG3MHuUCvn4nhg3GFOkXlAGHiZE4jqEbsBMdfovZy_KEl7HKcXaNp2bSPe5sR0G6QAQekcW63pEZ685MJ3E\",\r\n \"data\": {\r\n \"TicketId\":\"TICKETID-1060127\",\"NotificationCode\":null,\"NotificationMessage\":\"2\",\"NotificationType\":\"true\",\"NotificationData\":\"trip start\"\r\n }\r\n }\r\n}\r\n\r\n", null, "application/json"); // request.Content = content; var content = new StringContent("{\r\n \"message\": {\r\n \"token\":" + deviceid + ",\r\n \"data\": {" + strmessage + " }\r\n }\r\n}\r\n\r\n", null, "application/json"); request.Content = content; var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); success = response.Content.ReadAsStringAsync().ToString(); } catch (Exception Ex) { // write error log into file objLog.ErrorLogFile("Battery Voltage Error", Ex.Message, path, errorlogtf); } return success; } public async Task Autorefresh(string authtoken, string senderid, string deviceid, string strmessage) { string success = ""; try { /* var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/v1/projects/eicher-eos-androidx/messages:send"); request.Headers.Add("Sender", "15420367036"); request.Headers.Add("Authorization", "Bearer ya29.c.c0ASRK0GbdVuCP-BvvLkQXtLf-DhNcTntIOcOf56d2Mgr-xEvF_o1rtUYQJgLQfSaYT8uqmy51nEMWAHfCmPUdxJioSoizwiU1-hs0bhULM4zWRJdBWTcGW-IqSnew7Bn-bTP8spcgh7XdTOSqnz6e3bArXJdrtnrjutSzgoWwUBWGbs9VIGYp0kH9Rh2C0lu0F2EUR_SUTaLRTySuzT4fx-bI4FbAAN4f3z5K5dv8J4BnU35Vp0-eBYFQda9q3J0N9Y3KhPDKcBgY3OSFSSp0ukVDtYiuav7ZAt8rkwm1tlz982-9wLa1XurrNl2wneYt8RbtdA1ocwcOLu6hMQoFfmXovwiU-Ej-lsLmsbplS1L-WOFgfQxKtS8G384K0uzn1vXpnvbhFdB1kQxkguBWncVWcIctJ_jWUYFBYYs4b7YJmB8q4cvsuVmO27srQ2rtZfef3QnQ_pUvvUwMIi3un_YY5klIdzB_gSB8dSqworm1pgZXeRUskts2M2x5YU1rV0UzhhtX4RVibcWZ5MIzcWezvucO0xRc2nbUhlU7Zh03Yy2ejfJey_sunjuUMQhXh8pB4M9gUB7S4Y5Qfr-6zaXc_Xj1nx4Rvyq3YFghQtxFRSlt5vykVhBVdZoegedSqbz_S9jtcOMv8F_M6QtnZ-Opd1ufSF71V392UYdMz9ZBea1M1xVdme6p2nwlzbzkZv37qZ7oexUR6QnXfoZB0-ze9Q_8JxV7dMd1RV25ux7SzJFRnYOfQJ8Onf6_YlrOSqoWv_-fy4OiQ4xz6k_kMWqgZBa8wg0Z6eSJ9fwjj-QdcbVf2Vhyd-mRIcB3jns2-FSoQs67e9eYB88twuBFkvY974Z9pOo8ZUy0Z_ZB71rRj369avi7F1uk8I7JrR4ssy9Q-OMdzwf2yzfIWvyb0Y48swwe261pQpjboXIRfO3-Z6BMmmc4Z6JO_jx4xX4hzgZJIppRcdop6zs_BtmW9qQVWpvfaQwZUYs0Ridot8FVZFju2nlyVuk"); var content = new StringContent("{\r\n \"message\": {\r\n \"token\":\"d634BzVTQlU:APA91bEQMV8GR2ET7UHuOkXQGlKQrnBGQo_6v4AyI-QLUL6EvUwcUB6t0lv74QlmoQYfc2y9RTVm9Uz2ykrDK-y_iLBhlYWkHrWOfAjXwMXuSZiFUaBV8uY\",\r\n \"data\": {\r\n \"TicketId\":\"TICKETID-1046927\",\"NotificationCode\":null,\"NotificationMessage\":\"HI \"\r\n }\r\n }\r\n}\r\n\r\n", null, "application/json"); request.Content = content; var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); */ var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/v1/projects/eicher-eos-androidx/messages:send"); request.Headers.Add("Sender", senderid); request.Headers.Add("Authorization", "Bearer " + authtoken); var content = new StringContent("{\r\n \"message\": {\r\n \"token\":" + deviceid + ",\r\n \"data\": {" + strmessage + " }\r\n }\r\n}\r\n\r\n", null, "application/json"); request.Content = content; var response = await client.SendAsync(request); //response.EnsureSuccessStatusCode(); JObject parsedResponse = JObject.Parse(response.ToString()); string name = parsedResponse["name"].ToString(); Console.WriteLine(await response.Content.ReadAsStringAsync()); } catch (Exception Ex) { // write error log into file objLog.ErrorLogFile("Battery Voltage Error", Ex.Message, path, errorlogtf); } return success; } public string getdealerlatlong(string dealercode) { string strmessage = ""; try { NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("in_dealer_code", dealercode); DataSet ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_dealer_lat_Long"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { strmessage = Convert.ToString(ds.Tables[0].Rows[0]["sp_get_dealer_lat_Long"]); //strmessage = "success";//ds.Tables[0].Rows[0]["_ticket_id"].ToString(); // getting ticket id alias // errorlogtf = (ConfigurationManager.AppSettings["ErrorLog"]) + ticketIdAlias; } } catch (Exception Ex) { objLog.ErrorLogFile("getimeForSMS", Ex.Message, path, errorlogtf); } return strmessage; } public string getcurrentPreviousStatus(string ticket_id) { string strmessage = ""; try { NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("in_ticket_id", ticket_id); DataSet ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_prev_cur_status"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { strmessage = Convert.ToString(ds.Tables[0].Rows[0]["sp_get_prev_cur_status"]); //strmessage = "success";//ds.Tables[0].Rows[0]["_ticket_id"].ToString(); // getting ticket id alias // errorlogtf = (ConfigurationManager.AppSettings["ErrorLog"]) + ticketIdAlias; } } catch (Exception Ex) { objLog.ErrorLogFile("getimeForSMS", Ex.Message, path, errorlogtf); } return strmessage; } #region public List getRegistrationByEngines(string engine_Number) { List objList = new List(); try { NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inengine_number", NpgsqlTypes.NpgsqlDbType.Varchar); nSqlParam[0].Value = engine_Number; DataSet ds = NpgSqlHelper.ExecuteDataset( _connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_details_by_engine"], nSqlParam ); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new EngineDetailModel { creation_time = s.Field("creation_time").ToString("yyyy-MM-dd HH:mm:ss"), isdeleted = s.Field("isdeleted").ToString(), serial_no = s.Field("serial_no"), vehiclenumber = s.Field("vehiclenumber"), regno = s.Field("regno"), engine_class = s.Field("class"), chassis = s.Field("chassis"), engine_number = s.Field("engine"), vehiclemanufacturername = s.Field("vehiclemanufacturername"), model = s.Field("model"), vehiclecolour = s.Field("vehiclecolour"), type = s.Field("type"), owner_name = s.Field("owner_name"), mobilenumber = s.Field("mobilenumber"), status = s.Field("status"), statusason = s.Field("statusason") }).ToList(); } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository getRegistrationByEngines", Ex.Message, path, errorlogtf); throw; } return objList; } public List checkChassisNoandGetCustomerDetailEPS(CustomerModel model) { List objList = new List(); try { // String result = model.VehicleRegistrationNumber.Substring(model.VehicleRegistrationNumber.Length - 6); DataSet ds = new DataSet(); NpgsqlParameter[] nSqlParam = new NpgsqlParameter[1]; nSqlParam[0] = new NpgsqlParameter("inengine_number ", model.VehicleNumberPlate); ds = NpgSqlHelper.ExecuteDataset(_connStr, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_customer_engine_no_eps"], nSqlParam); if (ds.Tables[0].Rows.Count > 0) { objList = ds.Tables[0].AsEnumerable().Select(s => new CustomerModel { VehicleRegistrationNumber = s.Field("Odevice_alias") }).ToList(); } } catch (Exception Ex) { objLog.ErrorLogFile("GlobalRepository checkChassisNoandGetDetail", Ex.Message, path, errorlogtf); throw Ex; } return objList; } #endregion } #endregion }