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