0% found this document useful (0 votes)
4 views39 pages

Home

The document outlines the implementation of a HomeController for a web application that manages user login and call details. It includes methods for connecting to a SQL database, validating user credentials, retrieving user permissions, and generating search queries based on call details. The controller utilizes various libraries for logging, data handling, and SQL operations, ensuring secure and efficient management of user sessions and permissions.

Uploaded by

vu1f2021017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

Home

The document outlines the implementation of a HomeController for a web application that manages user login and call details. It includes methods for connecting to a SQL database, validating user credentials, retrieving user permissions, and generating search queries based on call details. The controller utilizes various libraries for logging, data handling, and SQL operations, ensuring secure and efficient management of user sessions and permissions.

Uploaded by

vu1f2021017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 39

using CCXWebServerSearch.

Helpers;
using CCXWebServerSearch.Models;
using ICSharpCode.SharpZipLib.Zip;
using Nexsus.Cryptography;
using Nexsus.MessageLog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Security;

namespace CCXWebServerSearch.Controllers
{
public class HomeController : Controller
{
public static MessageLogger Log = new
MessageLogger(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Log"));
public static string DBConnections = "Data Source=NEXSUS-DV62\\SQLEXPRESS;
Initial Catalog=CallConfineXWin; uid=sa; password=ccntspl@123";
SqlConnection con = new SqlConnection(DBConnections);
public static List<int> Permissions = new List<int>();
public static List<string> userpermissions = new List<string>();
CallDetails objCalldetails = new CallDetails();
MediaConverter objMediaConverter = new MediaConverter();
//static string constring =
getDBConnection.DecryptedConnectionString(DBConnections);
public static bool permission = false;
public static bool download = false;
private static bool checkConnection()
{
bool isConnected = false;
SqlConnection con = new SqlConnection(DBConnections);

try
{
Log.LogMessage(MessageLogger.MessageType.Info, "Attempting to
connect to database");
con.Open();
Log.LogMessage(MessageLogger.MessageType.Info, "Database connected
successfully.");
isConnected = true;
}
catch (Exception ex)
{
}

finally
{
if (con.State == ConnectionState.Open)
con.Close();
}

return isConnected;

[HttpGet]
public ActionResult Login()
{
Session.Clear();
Session.Abandon();
return View("Login");
}

[HttpPost]
public ActionResult Login(string uname, string pwd)
{
permission = false;
download = false;
try
{
if (String.IsNullOrEmpty(uname) || String.IsNullOrEmpty(pwd))
{
TempData["ErrorMessage"] = "Enter Username/Password";
return RedirectToAction("Login");
}
else
{
DBConnections = "Data Source=NEXSUS-DV62\\SQLEXPRESS; Initial
Catalog=CallConfineXWin; uid=sa; password=ccntspl@123";
if (checkConnection())
{
//string s =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;

//if (Membership.ValidateUser(uname, pwd))


using (SqlConnection conn = new
SqlConnection(DBConnections))
{

//var membership = Membership.GetUser(uname);


//// string[] a =
Roles.GetRolesForUser(membership.ToString());
//GetUserRole(uname);
//Session["UserRole"] = RoleDetails.Rows[0]
["RoleName"].ToString();

//Session["UserID"] = uname;
//Log.LogMessage(MessageLogger.MessageType.Info, "Login
Successfully.");
//return RedirectToAction("Index");
conn.Open();
string query = "Select UserId from tblUserDetails where
UserName = @uname AND UserPwd = @pwd";

using (SqlCommand cmd = new SqlCommand(query, conn))


{
cmd.Parameters.AddWithValue("@uname", uname);
cmd.Parameters.AddWithValue("@pwd", pwd);

//conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
//Login Successfull
if(reader.Read())
{
string userId =
reader["UserID"].ToString();
Session["UserID"] = userId;

Log.LogMessage(MessageLogger.MessageType.Info, "Login Successfully.");

GetUserPermissions(Convert.ToInt32(Session["UserID"]));
return RedirectToAction("Index");
}
else
{
TempData["ErrorMessage"] = "Invalid Username or
Password";
}
}
}
//else
//{
// TempData["ErrorMessage"] = "Invalid
Username/Password";
// return RedirectToAction("Login");
//}
}
else
{
TempData["ErrorMessage"] = "Try After Some Time";
return RedirectToAction("Login");
}

}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "In Login :" +
ex.Message);
TempData["Error"] = "ErrorOccured";
}
return View();
}

//============================EDITED===============================================
===//
public List<string> GetUserPermissions(int userId)
{

using (SqlConnection sqlconn = new SqlConnection(DBConnections))


{
using (SqlCommand cmd = new SqlCommand("SP_GetUserPermissions",
sqlconn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserID", userId);

sqlconn.Open();
SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
string permissionName =
reader["PermissionName"].ToString();
userpermissions.Add(permissionName);
}
}
}

return userpermissions;
}

//===========================================EDITED================================
=//
public ActionResult Index()
{
if (Session["UserID"] == null)
{
Session.Clear();
Session.Abandon();
return RedirectToAction("Login");
}
else
{
string userId = Convert.ToString(Session["UserID"]);
if (String.IsNullOrEmpty(userId))
{
Session.Clear();
Session.Abandon();
return RedirectToAction("Login");
}
else
{
string query2 = "Select PermissionID from tblUserProfile where
UserID=@userid";
using (SqlCommand cmd2 = new SqlCommand(query2, con))
{
cmd2.Parameters.AddWithValue("@userid",
Convert.ToInt32(Session["UserID"]));
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Permissions.Add(Convert.ToInt32(dr[0]));
}
Log.LogMessage(MessageLogger.MessageType.Info,
"Permissions added successfully !!.");
}
else
{
Log.LogMessage(MessageLogger.MessageType.Info, "There
is no permissions for current user !!.");
}
con.Close();
}

ViewBag.field1 = null;
ViewBag.field2 = null;
Session["Field1"] =
Convert.ToString(ConfigurationManager.AppSettings["Field1"]);
Session["Field2"] =
Convert.ToString(ConfigurationManager.AppSettings["Field2"]);
SqlConnection sqlconn = new SqlConnection(DBConnections);
SqlCommand cmd = new SqlCommand("select APDesc from
tblAppParameter where APDetail2 IN ('Field1','Field2') ", sqlconn);
cmd.CommandTimeout = 1000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet dsfields = new DataSet();
sda.Fill(dsfields);
DataTable fields = dsfields.Tables[0];

object[] showfield = new object[fields.Rows.Count];


int objNum = 0;
foreach (DataRow dr in fields.Rows)
{
var obj = new { Fields = Convert.ToString(dr["APDesc"]) };
showfield[objNum] = obj;
if (objNum == 0)
{
ViewBag.field1 = obj.Fields.ToString();
}
else
{
ViewBag.field2 = obj.Fields.ToString();
}
objNum++;
}
//ViewBag.ProcessData = showfield.fi;
return View();
}
}
}

private static string GetCallDetailsStringQuery(CallDetails details)


{
string searchQuery = "";
int extenFrom = 0;
int extenTo = 0;

if (details.ExtensFrom != "")
{
extenFrom = Convert.ToInt32(details.ExtensFrom);
}

if (details.ExtensTo != "")
{
extenTo = Convert.ToInt32(details.ExtensTo);
}

if (extenFrom != 0 && extenTo != 0)


{
searchQuery += "CAST(CallDetails.Extension as numeric) >='" +
extenFrom + "' AND CAST(CallDetails.Extension as numeric) <='" + extenTo + "' AND
";
}
else if (extenFrom != 0)
{
searchQuery += "CAST(CallDetails.Extension as numeric) ='" +
extenFrom + "' AND ";
}
else if (extenTo != 0)
{
searchQuery += "CAST(CallDetails.Extension as numeric) <='" +
extenTo + "' AND ";
}

if (details.CallerID != "")
{
searchQuery += "CallerID like '%" + details.CallerID + "%' AND ";
}

if (details.FromDate != "" && details.ToDate != "")


{

string[] fromda = details.FromDate.Split('-');


int fromDay = Convert.ToInt32(fromda[1]);
int fromMonth = Convert.ToInt32(fromda[0]);
int fromYear = Convert.ToInt32(fromda[2]);

DateTime DateFrom = new DateTime(fromYear, fromMonth, fromDay);


//string y=new DateTime()
string[] Toda = details.ToDate.Split('-');
int ToDay = Convert.ToInt32(Toda[1]);
int ToMonth = Convert.ToInt32(Toda[0]);
int ToYear = Convert.ToInt32(Toda[2]);

DateTime DateTo = new DateTime(ToYear, ToMonth, ToDay);


searchQuery += " CallDate >= '" + DateFrom.Date.ToString("yyyy-MM-
dd") + "' AND CallDate <= '" + DateTo.Date.ToString("yyyy-MM-dd") + "' AND ";
}

switch (details.CallType)
{
case "0": // all
searchQuery += " CallType >= 0 AND ";
break;
case "1": // In
searchQuery += " CallType = 1 AND ";
break;
case "2": //out
searchQuery += " CallType = 0 AND "; //0
break;
case "3": //miss
searchQuery += " CallType = 2 AND "; // 2
break;
case "4": //unknown
searchQuery += " CallType = 3 AND "; // 3
break;

if (details.FromTime != "" && details.ToTime != "")


{

DateTime TimeFrom = Convert.ToDateTime(details.FromTime);


DateTime TimeTo = Convert.ToDateTime(details.ToTime);
if (TimeFrom.TimeOfDay > TimeTo.TimeOfDay)
//strSQL += "CallDetailReports.CallTime >= '"+
myReport.DateFrom.Date.ToString("yyyy-MM-dd")+" "+
myReport.TimeFrom.ToString("HH:mm:ss")+"' OR CallDetailReports.CallTime <= '"+
myReport.DateTo.Date.ToString("yyyy-MM-dd")+" "+
myReport.TimeTo.ToString("HH:mm:ss")+"'";
searchQuery += " ((CallTime) - CAST(FLOOR(CAST((CallTime) AS
float)) AS datetime)>= '" + TimeFrom.ToString("HH:mm:ss") + "') OR ((CallTime)-
CAST(FLOOR(CAST((CallTime) AS float)) AS datetime)<= '" +
TimeTo.ToString("HH:mm:ss") + "' ) AND ";
else
//strSQL += "CallDetailReports.CallTime >= '"+
myReport.DateFrom.Date.ToString("yyyy-MM-dd")+" "+
myReport.TimeFrom.ToString("HH:mm:ss")+"' AND CallDetailReports.CallTime <= '"+
myReport.DateTo.Date.ToString("yyyy-MM-dd")+" "+
myReport.TimeTo.ToString("HH:mm:ss")+"'";
searchQuery += " ((CallTime) - CAST(FLOOR(CAST((CallTime) AS
float)) AS datetime)>= '" + TimeFrom.ToString("HH:mm:ss") + "') AND ((CallTime)-
CAST(FLOOR(CAST((CallTime) AS float)) AS datetime)<= '" +
TimeTo.ToString("HH:mm:ss") + "' ) AND ";
}

long durationFrom = 0;
if (details.CallDurStr != "")
{
string[] splitFrom = details.CallDurStr.Split(':');
durationFrom = Convert.ToInt32(splitFrom[0]) * 60 * 60 +
Convert.ToInt32(splitFrom[1]) * 60 + Convert.ToInt32(splitFrom[2]);
//durationFrom = Convert.ToInt32(txtDurationGrt.Text);
}
long durationTo = 0;
if (details.CallDurEnd != "")
{
string[] splitTo = details.CallDurEnd.Split(':');
durationTo = Convert.ToInt32(splitTo[0]) * 60 * 60 +
Convert.ToInt32(splitTo[1]) * 60 + Convert.ToInt32(splitTo[2]);
//durationTo = Convert.ToInt32(txtDurationLess.Text);
}

if (durationFrom != 0)
searchQuery += " Seconds >= " + durationFrom + " AND ";
if (durationTo != 0)
searchQuery += " Seconds <= " + durationTo + " AND ";
if (details.TransType != "All")
searchQuery += " TransType like '%" + details.TransType + "%' AND
";
if (details.CustID != "")
searchQuery += " CustID like '%" + details.CustID + "%' AND ";
if (details.AgentName != "")
searchQuery += " AgentMaster.AgentName like '%" +
details.AgentName + "%' AND ";
if (details.CallerName != "")
searchQuery += " (FirstName +' ' + MiddleName + ' ' + LastName)
like '%" + details.CallerName + "%' AND ";
if (details.IsRegistered != "All")
searchQuery += " CallDetails.IsRegistered = '" +
details.IsRegistered + "' AND ";
if (details.ClientCode != "")
searchQuery += " CallDetails.ClientCode = '" + details.ClientCode +
"' AND ";
if (details.UserName != "") //Field2
searchQuery += " CallDetails.Field2 like '%" + details.UserName +
"%' AND ";
if (details.Comment != "")
searchQuery += " Comment like '%" + details.Comment + "%' AND ";
if (details.AgentID != 0)
searchQuery += " CallDetails.AgentID = " + details.AgentID + " AND
";
if (details.Producttype != "") //Field1
searchQuery += " CallDetails.Field1 = '" + details.Producttype +
"' AND ";

return searchQuery;
}
public JsonResult GetCallDetails()
{
try
{
if (userpermissions.Contains("View Call Log"))
{

//StringBuilder stringBuilderQuery = new StringBuilder();


string searchQuery = "";

objCalldetails.ExtensFrom =
Convert.ToString(Request.Form["ExtensFrom"]);
objCalldetails.ExtensTo =
Convert.ToString(Request.Form["ExtensTo"]);
objCalldetails.CallerID =
Convert.ToString(Request.Form["CallerID"]);
objCalldetails.FromDate =
Convert.ToString(Request.Form["FromDate"]);
objCalldetails.ToDate =
Convert.ToString(Request.Form["ToDate"]);
objCalldetails.CallType =
Convert.ToString(Request.Form["CallType"]);
objCalldetails.FromTime =
Convert.ToString(Request.Form["FromTime"]);
objCalldetails.ToTime =
Convert.ToString(Request.Form["ToTime"]);
objCalldetails.CallDurStr =
Convert.ToString(Request.Form["CallDurStr"]);
objCalldetails.CallDurEnd =
Convert.ToString(Request.Form["CallDurEnd"]);
objCalldetails.TransType =
Convert.ToString(Request.Form["TransType"]);
objCalldetails.CustID =
Convert.ToString(Request.Form["CustID"]);
objCalldetails.AgentName =
Convert.ToString(Request.Form["AgentName"]);
objCalldetails.CallerName =
Convert.ToString(Request.Form["CallerName"]);
objCalldetails.IsRegistered =
Convert.ToString(Request.Form["IsRegistered"]);
objCalldetails.ClientCode =
Convert.ToString(Request.Form["ClientCode"]);
objCalldetails.Comment =
Convert.ToString(Request.Form["Comment"]);
objCalldetails.CallID =
Convert.ToString(Request.Form["CallID"]);

objCalldetails.UserName =
Convert.ToString(Request.Form["Field2"]); //Field2
if (Request.Form["AgentID"] == "")
objCalldetails.AgentID = 0;
else
objCalldetails.AgentID =
Convert.ToInt32(Request.Form["AgentID"]);
objCalldetails.Producttype =
Convert.ToString(Request.Form["Field1"]); //Field1

if (objCalldetails.CallID != "")
{
// stringBuilderQuery.Append(" CallDetails.CallID = '" +
CallID + "' AND ");
if (objCalldetails.CallID != "")
searchQuery += " CallDetails.CallID = '" +
objCalldetails.CallID + "' AND ";

searchQuery += GetCallDetailsStringQuery(objCalldetails);
string role = "";
if (Permissions.Count() == 39)
{
role = "Admin";
}
if (role == "Admin")
{

}
else
{
string userName = Convert.ToString(Session["UserID"]);
if (userName != null)
{
string userid = Session["UserID"].ToString();
//int count = CheckAllExtensionAssigned(userid);
//if (count == 0)
//{
switch (GetGroupByValue())
{
case 0:
break;
case 1:
searchQuery += " dbo.CallDetails.Extension
in (select AssignedExtension from AssignedExtension where UserID = '" + userid +
"') AND";
break;
}
//}

}
}

}
else
{

searchQuery += GetCallDetailsStringQuery(objCalldetails);
//string role = Session["UserRole"].ToString();
string role = "";
if (Permissions.Count() == 39)
{
role = "Admin";
}
if (role == "Admin")
{

}
else
{

string userName = Convert.ToString(Session["UserID"]);


if (userName != null)
{

//string userid = Session["UserID"].ToString();


//int count = CheckAllExtensionAssigned(userid);
//if (count == 0)
//{
//switch (GetGroupByValue())
//{
// case 0:
// break;
// case 1:
//searchQuery += " dbo.CallDetails.Extension in
(select AssignedExtension from AssignedExtension where UserID = '" + userid + "')
AND";
// break;
//}
//}
}
}

string finalQuery = searchQuery.Substring(0, searchQuery.Length


- 4);
//string finalQuery =
Convert.ToString(stringBuilderQuery.Remove(stringBuilderQuery.Length - 4,
stringBuilderQuery.Length));

SqlConnection sqlconn = new SqlConnection(DBConnections);


SqlCommand cmd = new SqlCommand("SP_GetFilteredCallDetails",
sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("@SearchQuery", finalQuery);
cmd.Parameters.AddWithValue("@ekey", "NexCC8198(@12fine");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);

DataTable callDetails = ds.Tables[0];


// Add the "Play" column to the DataTable
//callDetails.Columns.Add("Play", typeof(string));

//// Populate the "Play" column with HTML for play button
//foreach (DataRow row in callDetails.Rows)
//{
// // Assuming CallerID is a unique identifier for the call
details
// string callerId = row["CallerID"].ToString(); // Replace
"CallerID" with your unique identifier column
// row["Play"] = "<span id=\"" + callerId + "\" ><img
src=\"../Content/images/play_1A.png\" id=\"" + callerId + "\"
onclick=\"ShowAudioPlayer(this)\" /></span>";
//}
if (userpermissions.Contains("Play Calls"))
{
callDetails.Columns.Add("Play", typeof(string));

// Populate the "Play" column with HTML for play button


foreach (DataRow row in callDetails.Rows)
{
string callerId =
HttpUtility.HtmlEncode(row["CallerID"].ToString()); // Escape HTML
string fileName =
HttpUtility.HtmlEncode(row["FileName"].ToString()); // Assuming you have the file
name in a column

// Ensure the image path is correct


string playButtonHtml = $"<span id=\"{callerId}\" aria-
label=\"Play audio for call {callerId}\">" +
$"<img
src=\"../Content/images/play_1A.png\" id=\"{callerId}\" " +

$"onclick=\"ShowAudioPlayer('{callerId}', '{fileName}')\" alt=\"Play button\"


/></span>";

row["Play"] = playButtonHtml;
}
}

if (userpermissions.Contains("Send To"))
{
callDetails.Columns.Add("Download", typeof(string)); // Add
Download column

// Populate the "Download" column with HTML for download


button
foreach (DataRow row in callDetails.Rows)
{
string callerId =
HttpUtility.HtmlEncode(row["CallerID"].ToString()); // Escape HTML
string fileName =
HttpUtility.HtmlEncode(row["FileName"].ToString()); // Assuming you have the file
name in a column

// Create the download button HTML using the specified


image
string downloadButtonHtml = $"<span id=\"{callerId}\"
aria-label=\"Download audio for call {callerId}\">" +
$"<a href=\"/Home/DownloadFileAudio?
fileName={HttpUtility.UrlEncode(fileName)}\">" +
$"<img src=\"../Content/images/download-
(1A).png\" alt=\"Download button\" /></a></span>";

row["Download"] = downloadButtonHtml; // Set the


Download column with the button HTML
}
}

callDetails.DefaultView.Sort = "CallTime asc";


callDetails = callDetails.DefaultView.ToTable(true);

string totalCallDetails =
Convert.ToString(callDetails.Rows.Count);
Session["CallDetails"] = callDetails;

Dictionary<string, string> colPropPair = new Dictionary<string,


string>();
string propNamePref = "Prop";
string theadContent = "";

for (int i = 0; i < callDetails.Columns.Count; i++)


{
theadContent += "<th>" + callDetails.Columns[i].ColumnName
+ "</th>";
colPropPair.Add(propNamePref + i,
callDetails.Columns[i].ColumnName);
}

object[] columnBindData = new object[colPropPair.Count];


int objNum = 0;

foreach (KeyValuePair<string, string> pair in colPropPair)


{
var obj = new { data = pair.Key, name = pair.Value,
autoWidth = true };
columnBindData[objNum] = obj;
objNum++;
}

return Json(
new
{
Status = "1",
Message = "",
TheadContent = theadContent,
ColBindData = columnBindData,
totalCallDetails = totalCallDetails
});

}
else
{
return Json(RedirectToAction("Index"));
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
GetCalldetails()." + ex.Message);
return Json(
new
{
Status = "0",
Message = ex.Message,
TheadContent = "",
ColBindData = ""
});
}
}

/*Changes*/
public ActionResult DownloadFileAudio(string fileName)
{
string[] parts = fileName.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
// Extract the date part from the filename
string datePart = parts[1]; // "02-15-2022"
string[] dateComponents = datePart.Split('-'); // ["02", "15",
"2022"]

if (dateComponents.Length == 3)
{
string month = dateComponents[0]; // "02"
string day = dateComponents[1]; // "15"
string year = dateComponents[2]; // "2022"

// Construct the correct file path


string folderPath = Path.Combine(@"D:\UlogFolder\NexsusCIL",
year, GetMonthName(month), day);
string filePath = Path.Combine(folderPath, fileName);
if (System.IO.File.Exists(filePath))
{
byte[] fileBytes =
System.IO.File.ReadAllBytes(filePath); // Read the file bytes
return File(fileBytes, "application/octet-stream",
Path.GetFileName(filePath)); // Return file for download
}
}
}
return HttpNotFound(); // Return 404 if the file does not exist
}

private string GetMonthName(string monthNumber)


{
switch (monthNumber)
{
case "01": return "JANUARY";
case "02": return "FEBRUARY";
case "03": return "MARCH";
case "04": return "APRIL";
case "05": return "MAY";
case "06": return "JUNE";
case "07": return "JULY";
case "08": return "AUGUST";
case "09": return "SEPTEMBER";
case "10": return "OCTOBER";
case "11": return "NOVEMBER";
case "12": return "DECEMBER";
default: return null; // Invalid month
}
}

/*Changes*/

[HttpPost]
public void PlayRecordedCall(string FileName)
{
System.Media.SoundPlayer wavPlayer = new System.Media.SoundPlayer();
wavPlayer.SoundLocation = FileName;
wavPlayer.Play();
}

private DataTable ReadToEnd(string filepath)


{
try
{
DataTable dtDataSource = new DataTable();
string[] fileContent = System.IO.File.ReadAllLines(filepath);
if (fileContent.Count() > 0)
{
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split(',');
dtDataSource.Rows.Add(rowData);
}
}
return dtDataSource;
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error while
reading CSVFile in ReadToEnd()." + ex.Message);
return null;
}
}

[HttpPost]
public ActionResult LoadData(string DataCategory, bool isIevalue)
{
List<string> userPermissions =
GetUserPermissions(Convert.ToInt32(Session["UserID"]));
try
{
if (DataCategory != null)
{
string searchText = "", draw = "", start = "", length = "",
sortColumnDir = "", className = "";
int sortColumnPos;

draw = Request.Form.GetValues("draw").FirstOrDefault();
start = Request.Form.GetValues("start").FirstOrDefault();
length = Request.Form.GetValues("length").FirstOrDefault();
sortColumnPos =
Convert.ToInt16(Request.Form.GetValues("order[0][column]").FirstOrDefault());
sortColumnDir = Request.Form.GetValues("order[0]
[dir]").FirstOrDefault();
searchText =
Request.Form.GetValues("search[value]").FirstOrDefault();

int pageSize = length != null ? Convert.ToInt32(length) : 0;


int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
DataTable dt;

if (DataCategory.ToUpper() == "RECONCILED")
{
if (Session["FinalOutput"] != null)
{
dt = Session["FinalOutput"] as DataTable;
className = "ReconData";
}
else
{
Session.Clear();
Session.Abandon();
return Json(new { draw = 0, recordsFiltered = 0,
recordsTotal = 0, data = "", statusFlag = "failed", redirectUrl = "/Home/Login" },
JsonRequestBehavior.AllowGet);
}
}
else if (DataCategory.ToUpper() == "CALLDETAILS")
{
if (Session["CallDetails"] != null)
{
dt = Session["CallDetails"] as DataTable;
className = "CallDetailsData";
}
else
{
Session.Clear();
Session.Abandon();
return Json(new { draw = 0, recordsFiltered = 0,
recordsTotal = 0, data = "", statusFlag = "failed", redirectUrl = "/Home/Login" },
JsonRequestBehavior.AllowGet);
}
}
else
{
dt = new DataTable();
className = "NA";

Log.LogMessage(MessageLogger.MessageType.Error, "Invalid
DataCategory of Grid data.");
return Json(new { draw = 0, recordsFiltered = 0,
recordsTotal = 0, data = "", statusFlag = "error" }, JsonRequestBehavior.AllowGet);
}

string sortColumn = dt.Columns[sortColumnPos].ColumnName;

DataView dv = new DataView(dt);


if (!(string.IsNullOrEmpty(sortColumn) &&
string.IsNullOrEmpty(sortColumnDir)))
{
dv.Sort = "[" + sortColumn + "]" + " " + sortColumnDir;
}
if (!(string.IsNullOrEmpty(searchText)))
{
string filter = "";
int colCount = dt.Columns.Count;
for (int i = 0; i < colCount; i++)
{
filter += "Convert([" + dt.Columns[i].ColumnName + "],
System.String)" + " LIKE '%" + searchText + "%'";
if (i < (colCount - 1))
{
filter += " OR ";
}
}
dv.RowFilter = filter;
}

DataTable dtFinal = dv.ToTable();

string[] propNames = new string[dtFinal.Columns.Count];


Type[] propTypes = new Type[dtFinal.Columns.Count];
Dictionary<string, string> colPropPair = new Dictionary<string,
string>();
string propNamePref = "Prop";
for (int i = 0; i < dtFinal.Columns.Count; i++)
{
colPropPair.Add(propNamePref + i,
dtFinal.Columns[i].ColumnName);
propNames[i] = propNamePref + i;
propTypes[i] = typeof(string);
}

DynamicClassBuilder DCB = new DynamicClassBuilder(className);


object objClassData = DCB.CreateObject(propNames, propTypes);
IList lstClassData =
(IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new Type[]
{ objClassData.GetType() }));

foreach (DataRow dataRow in dtFinal.Rows)


{
var objClass =
Activator.CreateInstance(objClassData.GetType());
int i = 0;
PropertyInfo[] properties =
objClass.GetType().GetProperties();

foreach (PropertyInfo property in properties)


{
string columnName = colPropPair[propNamePref + i];

if (className == "ReconData")
{

}
else if (className == "CallDetailsData")
{
if (columnName == "Select")
{
string callerid =
dataRow[columnName].ToString();
property.SetValue(objClass, "<input
type=\"checkbox\" class=\"chkCheckBoxId\" id=\"" + callerid + "\" name=\"ID\"
value=\"" + callerid + "\">");
}
//else if (columnName == "Play")
//{
// //string userrole =
Session["UserRole"].ToString();
// //bool ispermission =
PlayPermission(userrole);
// if (userPermissions.Contains("Play Calls"))
// {
// string callerid =
dataRow[columnName].ToString();
// property.SetValue(objClass, "<span id=\""
+ callerid + "\" ><img src=\"../Content/images/play_1A.png\" id=\"" + callerid +
"\" onclick=\"ShowAudioPlayer(this)\" /></span>");

// }
// else
// {
// string callerid =
dataRow[columnName].ToString();
// //property.SetValue(objClass, "<span
id=\"" + callerid + "\" class=\"glyphicon glyphicon-play\" style=\"font-
size:20px;\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"You Don't
have Permission to Play Calls.\" ></span>");
// property.SetValue(objClass, "<span id=\""
+ callerid + "\" ><img src=\"../Content/images/Play_2.png\" id=\"" + callerid + "\"
data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"You Don't have Permission
to Play Calls.\" /></span>");

// }
//}
//else if (columnName == "Download")
//{
// string userrole =
Session["UserRole"].ToString();
// bool ispermission =
DownloadPermission(userrole);
// if (ispermission)
// {
// string callerid =
dataRow[columnName].ToString();
// string a =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) +
Request.ApplicationPath);
// //property.SetValue(objClass, "<span
id=\"" + dataRow[columnName].ToString() + "\" class=\"glyphicon glyphicon-play\"
style=\"font-size:20px;\" onclick=\"ShowAudioPlayer(this)\"></span>");
// property.SetValue(objClass, "<span id=\""
+ callerid + "\" ><img src=\"../Content/images/download-(1A).png\" id=\"" +
callerid + "\" onclick=\"GetByID(id)\" /></span>");
// //property.SetValue(objClass, " <a id=\""
+ callerid + "\" class=\"glyphicon glyphicon-download-alt\" style=\"font-
size:20px;\" onclick=\"GetByID(id)\" ></a>");

// }
// else
// {
// string callerid =
dataRow[columnName].ToString();
// //property.SetValue(objClass, "<span
id=\"" + callerid + "\" class=\"glyphicon glyphicon-download-alt\" style=\"font-
size:20px;\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"You Don't
have Permission to Download Calls.\" ></span>");
// property.SetValue(objClass, "<span id=\""
+ callerid + "\" ><img src=\"../Content/images/download_1.png\" id=\"" + callerid +
"\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"You Don't have
Permission to Download Calls.\" /></span>");

// }

//}
else
{
property.SetValue(objClass,
dataRow[columnName].ToString());
}
}
else
{
property.SetValue(objClass,
dataRow[columnName].ToString());
}

i++;
}

lstClassData.Add(objClass);
}

List<object> lstReconObj =
lstClassData.Cast<object>().ToList<object>();
recordsTotal = lstReconObj.Count;
var data = lstReconObj.Skip(skip).Take(pageSize).ToList();

#region Log Filtered Json data


//Log.LogMessage(MessageLogger.MessageType.Info, "In
LoadData(), Json string of Filtered List is");
//string output =
Newtonsoft.Json.JsonConvert.SerializeObject(data);
//Log.LogMessage(MessageLogger.MessageType.Info, output);
#endregion

return Json(new { draw = draw, recordsFiltered = recordsTotal,


recordsTotal = recordsTotal, data = data, statusFlag = "success" },
JsonRequestBehavior.AllowGet);
}
else
{
Log.LogMessage(MessageLogger.MessageType.Error, "Datacategory
for Loading Grid not specified.");
return Json(new { draw = 0, recordsFiltered = 0, recordsTotal =
0, data = "", statusFlag = "error" }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
LoadData()." + ex.Message);
return Json(new { draw = 0, recordsFiltered = 0, recordsTotal = 0,
data = "", statusFlag = "error" }, JsonRequestBehavior.AllowGet);
}
}

[HttpPost]
public ActionResult PlayAudioFile(string callID)
{
string FinalPath = @"D:\UlogFolder\NexsusCIL\2022\FEBRUARY\15"; // New
path
string file = "";
string fileName = "";
string OutputFileName = "";
string filepath = "";
string PlayPath = "";
string Final = "";

try
{
if (!callID.Contains(':'))
{
if (!string.IsNullOrEmpty(callID))
{
string userName = Convert.ToString(Session["UserID"]);
if (userName != null)
{
string userid = Session["UserID"].ToString();
file = callID;

// Generate full file path from new base directory


string fullFilePath = Path.Combine(FinalPath, file);
string playFile = playFileInView(fullFilePath);
if (playFile.StartsWith("//"))
{
FinalPath = playFile;
}
else
{
FinalPath =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) + playFile);
}

FinalPath = FinalPath.Replace(@"\", @"/");


fileName = FinalPath.Split('/').Last();

if (fileName.StartsWith("S"))
{
string ip = GetIpAddress().ToString();
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "tempvoicefile", userid,
ip);
if (!Directory.Exists(OutputFileName))
{
Directory.CreateDirectory(OutputFileName);
}

filepath = Path.Combine(OutputFileName, fileName);


string decryptedfilepath = OutputFileName + @"\" +
fileName;

bool isDecrypted = Cryptography.DecryptFile(file,


decryptedfilepath);
if (isDecrypted)
{
PlayPath =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) +
Request.ApplicationPath + "/tempvoicefile/" + userid + "/" + ip + "/" + fileName);
Final = PlayPath;
}
}
else
{
WebClient client = new WebClient();
if (FinalPath.StartsWith("//"))
{
string ip = GetIpAddress().ToString();
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "tempvoicefile", userid,
ip);
if (!Directory.Exists(OutputFileName))
{
Directory.CreateDirectory(OutputFileName);
}

filepath = Path.Combine(OutputFileName,
fileName);

if (!System.IO.File.Exists(filepath))
{
client.
UploadFile(FinalPath, filepath);
}

if (System.IO.File.Exists(filepath))
{
PlayPath =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) +
Request.ApplicationPath + "/tempvoicefile/" + userid + "/" + ip + "/" + fileName);
Final = PlayPath;
}
}
}
}
else
{
return RedirectToAction("Login");
}
}
}
else
{
file = callID;
FileInfo f = new FileInfo(file);

if (f.Extension == ".awb" || f.Extension == ".amr")


{
// Add specific handling logic here if required
}
else
{
string strFile = file.Replace(@"\", @"/");
string playFile = playFileInView(file);
FinalPath = playFile.Replace(@"\", @"/");

fileName = FinalPath.Split('/').Last();

if (fileName.StartsWith("S"))
{
string userName = Convert.ToString(Session["UserID"]);
if (userName != null)
{
string userid = Session["UserID"].ToString();
string ip = GetIpAddress().ToString();
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "tempvoicefile", userid,
ip);
if (!Directory.Exists(OutputFileName))
{
Directory.CreateDirectory(OutputFileName);
}

filepath = Path.Combine(OutputFileName, fileName);


string decryptedfilepath = OutputFileName + @"\" +
fileName;

bool isDecrypted = Cryptography.DecryptFile(file,


decryptedfilepath);
if (isDecrypted)
{
PlayPath =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) +
Request.ApplicationPath + "/tempvoicefile/" + userid + "/" + ip + "/" + fileName);
Final = PlayPath;
}
}
else
{
return RedirectToAction("Login");
}
}
else
{
FileInfo f1 = new FileInfo(file);
if (f1.Extension == ".729")
{
string playfile = playFile.Replace(@"\", @"/");
string play = playFileInView(playfile);

fileName = FinalPath.Split('/').Last();

FinalPath =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) +
Request.ApplicationPath + "/tempvoicefile/mp3/" + fileName);
Final = FinalPath;
}
else
{
FinalPath =
Convert.ToString(Request.Url.GetLeftPart(UriPartial.Authority) + playFile);
Final = FinalPath;
}
}
}
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Play
File(Exception): " + ex.Message + " Play File Path: " + Final);
}

return Json(new { output = Final, fileName = fileName });


}

public static string playFileInView(string file)


{
string strFile = file.Replace(@"\", @"/");
FileInfo f = new FileInfo(strFile);
if (f.Extension == ".729")
{
try
{
strFile = MediaConverter.convertFile(strFile.Split('/').Last(),
strFile);
if (strFile == null)
{
return strFile;
}
else
{
return strFile;
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
convertFile()." + ex.Message);
}

if (strFile.StartsWith("//")) //For network path


strFile = strFile;
//strFile = strFile.Substring(strFile.IndexOf(@"/", 4));
else
strFile = strFile.Remove(0, 2); //For local path
return strFile;
}

//This Method is created to Check Whether the user have Permission to play
call or not.
public bool PlayPermission(string uname)
{
int a = 0;
DBConnections =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
//if (checkConnection())
//{
SqlConnection sqlconn = new SqlConnection(DBConnections);
SqlCommand cmd = new SqlCommand("GetRoles", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("@Roles", uname);
cmd.Parameters.AddWithValue("@Permission", "Play Calls");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);

DataTable Details = ds.Tables[0];


a = Details.Rows.Count;
if (a == 0)
{
permission = false;
}
else
{
permission = true;
}
//Log.LogMessage(MessageLogger.MessageType.Error, "Play Call Count:" +
a);
////}
return permission;
}

DataTable RoleDetails;
public void GetUserRole(string uname)
{

DBConnections =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
//if (checkConnection())
//{
//SqlConnection sqlconn = new SqlConnection(DBConnections);
//SqlCommand cmd = new SqlCommand("GetUserRole_CCXWebSearch", sqlconn);
//cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandTimeout = 0;
//cmd.Parameters.AddWithValue("@Username", uname);
//SqlDataAdapter sda = new SqlDataAdapter(cmd);
//DataSet ds = new DataSet();
//sda.Fill(ds);
//RoleDetails = ds.Tables[0];

SqlConnection sqlconn = new SqlConnection(DBConnections);


SqlCommand cmd = new SqlCommand("Reconcile_SP_GetUserRole", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", uname);
cmd.Parameters.AddWithValue("@ApplicationName",
Membership.ApplicationName);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
RoleDetails = ds.Tables[0];

//}
}

//This Method is created to Check Whether the user have Permission to


Download call or not.
public bool DownloadPermission(string uname)
{
int a = 0;
DBConnections =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
//if (checkConnection())
//{
SqlConnection sqlconn = new SqlConnection(DBConnections);
SqlCommand cmd = new SqlCommand("GetRoles", sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("@Roles", uname);
cmd.Parameters.AddWithValue("@Permission", "Manage Download");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);

DataTable Details = ds.Tables[0];


a = Details.Rows.Count;
if (a == 0)
{
download = false;
}
else
{
download = true;
}
//}
return download;
}

[HttpPost]
public ActionResult GetById(object[] ID)
{

try
{
//int count = 0;
string FinalPath = "";
string file = "";
string fileName = "";
string path = ID[0].ToString();
string[] a = path.Split(',');
//int TotalCount = a.Count();
string OutputFileName = "";
string filepath = "";
//string DownloadPath = "";
//string Final = "";
string decryptedfilepath = "";

//ArrayList paths = new ArrayList();


//ArrayList Filename = new ArrayList();

if (a.Count() > 1)
{
try
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < a.Length; i++)
{
try
{
file = a[i];
string strFile = file.Replace(@"\", @"/");
string downloadFile = playFileInView(file);
if (downloadFile.StartsWith("//"))
FinalPath = downloadFile;
else
FinalPath = file;

FinalPath = FinalPath.Replace(@"\", @"/");


// Log.LogMessage(MessageLogger.MessageType.Error,
"File" + FinalPath);
//paths.Add(FinalPath);
//if (downloadFile != null)
//{
// fileName = FinalPath.Split('/').Last();
// Filename.Add(fileName);
//}
fileName = FinalPath.Split('/').Last();

if (fileName.StartsWith("S"))
{
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
if (!Directory.Exists(OutputFileName))
Directory.CreateDirectory(OutputFileName);

filepath = Path.Combine(OutputFileName,
fileName);

decryptedfilepath = OutputFileName + @"\" +


fileName;

bool isDecrypted =
Cryptography.DecryptFile(file, decryptedfilepath);
if (isDecrypted)
{
s.Append(decryptedfilepath + ",");

//Log.LogMessage(MessageLogger.MessageType.Info, "Play File Path: " + Final);


}

}
else
{
if (System.IO.File.Exists(file))
{
string audiourl = file.ToString();
string audiofilechang =
audiourl.Replace(@"\", @"/");
string audiofile =
audiofilechang.Split('/').Last();
FileInfo f = new FileInfo(audiofile);
if (f.Extension == ".awb" || f.Extension ==
".amr")
{

OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
if (!Directory.Exists(OutputFileName))

Directory.CreateDirectory(OutputFileName);

//filepath =
Path.Combine(OutputFileName, audiofile);
string finalfilename =
audiofile.Substring(0, audiofile.Length - 4) + ".mp3";
decryptedfilepath = OutputFileName +
@"\" + finalfilename;
bool isDecrypted =
Convertawbtomp3(file, decryptedfilepath);
if (isDecrypted)
{
s.Append(decryptedfilepath + ",");
}
}
else
{
s.Append(file + ",");
}

//return Json(new { Success = "success",


Path = s, Downloadtype = "Multiple" }, JsonRequestBehavior.AllowGet);
}
else
{

Log.LogMessage(MessageLogger.MessageType.Info, "Download File Path: " + file);


}
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error,
"Downloading File:" + file);
}
}
string x = s.ToString();
return Json(new { Success = "success", Path = x,
Downloadtype = "Multiple" }, JsonRequestBehavior.AllowGet);

}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error,
"Downloading File:" + file);
}
}
else
{

OutputFileName = "";
FinalPath = "";
filepath = "";

file = ID[0].ToString();

FileInfo f = new FileInfo(file);

if (f.Extension == ".awb" || f.Extension == ".amr")


{
//string strFile = file.Replace(@"\", @"/");
string downloadFile = file;
if (downloadFile.StartsWith("//"))
FinalPath = downloadFile;
else
FinalPath = downloadFile;
FinalPath = FinalPath.Replace(@"\", @"/");
try
{
string audiourl = FinalPath.ToString();
string audiofile = audiourl.Split('/').Last();
if (audiofile.StartsWith("S"))
{
if (System.IO.File.Exists(file))
{
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
if (!Directory.Exists(OutputFileName))
Directory.CreateDirectory(OutputFileName);

//filepath = Path.Combine(OutputFileName,
audiofile);
string finalfilename = audiofile.Substring(0,
audiofile.Length - 4) + ".mp3";
decryptedfilepath = OutputFileName + @"\" +
finalfilename;

bool isDecrypted =
Cryptography.DecryptFile(file, decryptedfilepath);
if (isDecrypted)
{
return Json(new { Success = "success", Path
= decryptedfilepath, Downloadtype = "single" }, JsonRequestBehavior.AllowGet);
}

}
else
{
Log.LogMessage(MessageLogger.MessageType.Info,
"Download File Path: " + ID);
}

}
else
{

if (System.IO.File.Exists(file))
{
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
if (!Directory.Exists(OutputFileName))
Directory.CreateDirectory(OutputFileName);

//filepath = Path.Combine(OutputFileName,
audiofile);
string finalfilename = audiofile.Substring(0,
audiofile.Length - 4) + ".mp3";
decryptedfilepath = OutputFileName + @"\" +
finalfilename;

bool isDecrypted = Convertawbtomp3(file,


decryptedfilepath);
if (isDecrypted)
{
return Json(new { Success = "success", Path
= decryptedfilepath, Downloadtype = "single" }, JsonRequestBehavior.AllowGet);
}

}
else
{
Log.LogMessage(MessageLogger.MessageType.Info,
"Download File Path: " + ID);
}

}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error,
"Download File Path: " + ID);
}
}
else
{

try
{
string strFile = file.Replace(@"\", @"/");
string downloadFile = playFileInView(file);
FileInfo f1 = new FileInfo(file);
if (f1.Extension == ".729")
{
if (System.IO.File.Exists(downloadFile))
{
return Json(new { Success = "success", Path =
downloadFile, Downloadtype = "single" }, JsonRequestBehavior.AllowGet);
}
}

if (downloadFile.StartsWith("//"))
FinalPath = downloadFile;
else
FinalPath = downloadFile;

FinalPath = FinalPath.Replace(@"\", @"/");


string audiourl = FinalPath.ToString();
string audiofile = audiourl.Split('/').Last();
if (audiofile.StartsWith("S"))
{
if (System.IO.File.Exists(file))
{
OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
if (!Directory.Exists(OutputFileName))
Directory.CreateDirectory(OutputFileName);

filepath = Path.Combine(OutputFileName,
audiofile);

decryptedfilepath = OutputFileName + @"\" +


audiofile;
bool isDecrypted =
Cryptography.DecryptFile(file, decryptedfilepath);
if (isDecrypted)
{
return Json(new { Success = "success", Path
= decryptedfilepath, Downloadtype = "single" }, JsonRequestBehavior.AllowGet);
}

}
else
{
Log.LogMessage(MessageLogger.MessageType.Info,
"Download File Path: " + ID);
}

}
else
{
//OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
//if (!Directory.Exists(OutputFileName))
// Directory.CreateDirectory(OutputFileName);

//filepath = Path.Combine(OutputFileName,
audiofile);

//string decryptedfilepath = OutputFileName + @"\"


+ audiofile;

//bool isDecrypted = Cryptography.DecryptFile(file,


decryptedfilepath);
//////
//OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Downloadvoicefile");
//if (!Directory.Exists(OutputFileName))
// Directory.CreateDirectory(OutputFileName);

//filepath = Path.Combine(OutputFileName,
fileName);

//string decryptedfile = OutputFileName + @"\" +


fileName;

//bool isDecrypted = Cryptography.DecryptFile(file,


decryptedfile);
if (System.IO.File.Exists(file))
{
return Json(new { Success = "success", Path =
file, Downloadtype = "single" }, JsonRequestBehavior.AllowGet);
}
else
{
Log.LogMessage(MessageLogger.MessageType.Info,
"Download File Path: " + file);
}

}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error,
"Download File Path: " + ID);
}

return Json(new { Success = "success" },


JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
GetById().");
return Json(ex);
}

public ActionResult MultipleDownload(string file)


{
string tempFileName = "";
try
{
string[] filesCol = file.Split(',');
string audiofile = "";

byte[] buffer = new byte[4096];

if (!
System.IO.Directory.Exists(Path.Combine(HostingEnvironment.ApplicationPhysicalPath
+ "TempZipFile")))
{

System.IO.Directory.CreateDirectory(Path.Combine(HostingEnvironment.ApplicationPhys
icalPath + "TempZipFile"));
}

// the path on the server where the temp file will be created!
tempFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath + "TempZipFile" + "\\
MyZip.zip");

ZipOutputStream zipOutputStream = new


ZipOutputStream(System.IO.File.Create(tempFileName));
string filePath = String.Empty;
string fileName = String.Empty;
int readBytes = 0;
int countFiles = 0;

for (int i = 0; i < filesCol.Count() - 1; i++)


{

filePath = filesCol[i];
string files = filesCol[i].Replace(@"\", @"/");
fileName = files.Split('/').Last();

FileInfo fi = new FileInfo(filePath);


if (fi.Exists)
{
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.PutNextEntry(zipEntry);

using (FileStream fs = System.IO.File.OpenRead(filePath))


{
do
{
readBytes = fs.Read(buffer, 0, buffer.Length);
zipOutputStream.Write(buffer, 0, readBytes);
} while (readBytes > 0);

}
countFiles++;
Log.LogMessage(MessageLogger.MessageType.Info, "Filepath:"
+ filePath);
}
else
{
Log.LogMessage(MessageLogger.MessageType.Info, "File not
Found : " + filePath);
}
}

zipOutputStream.Finish();
zipOutputStream.Close();

Response.ContentType = "application/x-zip-compressed";
//Response.AppendHeader("Content-Disposition", "attachment;
filename=" + DateTime.Now.ToString("MM/dd/yyyy HH:mm") + ".zip");
Response.AddHeader("Content-Disposition", "attachment; filename=" +
DateTime.Now.ToString("MM/dd/yyyy HH:mm") + ".zip");
Int64 fileSizeInBytes = new FileInfo(tempFileName).Length;
Response.AddHeader("Content-Length", fileSizeInBytes.ToString());
Response.WriteFile(tempFileName);

Response.Flush();
Response.Close();
Log.LogMessage(MessageLogger.MessageType.Info, "Sucessfully
Downloaded Zip File");

if (System.IO.File.Exists(tempFileName))
System.IO.File.Delete(tempFileName);
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, ex.ToString());
}

return View(); //It is a Empty View.


}

public void DownloadAudio(string downloadpath)


{
if (!string.IsNullOrEmpty(downloadpath) &&
System.IO.File.Exists(downloadpath))
{
try
{
Response.Clear();
string filepath = downloadpath.Replace(@"\", @"/");
string filename = filepath.Split('/').Last();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;
filename=" + filename);
Response.TransmitFile(downloadpath);
Log.LogMessage(MessageLogger.MessageType.Info, "Downloading
file: " + downloadpath);
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error
downloading file: " + ex.Message);
}
finally
{
Response.End();
}
}
else
{
Response.StatusCode = 404;
Response.StatusDescription = "File not found";
Response.End();
}
}

public ActionResult DownloadExcel(string file)


{
try
{
if (file != null)
{
string fileName = Path.GetFileName(file);
return File(file, "application/vnd.ms-excel", fileName);
}
else
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
DownloadExcel().");
return RedirectToAction("Index");
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
DownloadExcel()." + ex.Message);
return RedirectToAction("Index");
}
}

[HttpPost]
public ActionResult GetPath(string FileCategory)
{
try
{
if (FileCategory.ToUpper() == "RECONCILED")
{
return Json(new { Success = "failed", FileName =
"/Home/Login" }, JsonRequestBehavior.AllowGet);

}
else if (FileCategory.ToUpper() == "CALLDETAILS")
{
DataTable dtCallDetails = Session["CallDetails"] as DataTable;
ExportToExcel(dtCallDetails, DateTime.Now.ToString("dd-MM-
yyyy"), "CallDetails");

if (Session["CallDetailsExcelPath"] != null)
{
string fileSavePath =
Session["CallDetailsExcelPath"].ToString();
return Json(new { Success = "success", FileName =
fileSavePath }, JsonRequestBehavior.AllowGet);
}
else
{
Session.Clear();
Session.Abandon();
Log.LogMessage(MessageLogger.MessageType.Error, "Error
while getting filePath of CALLDETAILS from Session in GetPath().");
return Json(new { Success = "failed", FileName =
"/Home/Login" }, JsonRequestBehavior.AllowGet);
}
}
else
{
Log.LogMessage(MessageLogger.MessageType.Error, "Incorrect file
requested.");
return Json(new { Success = "error" },
JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error occured in
GetPath()." + ex.Message);
return Json(new { Success = "error" },
JsonRequestBehavior.AllowGet);
}
}

public void ExportToExcel(DataTable dtToExcel, string date, string


DataCategory)
{
string OutputFileName = "", info = "";
if (DataCategory.ToUpper() == "RECONCILED")
{
OutputFileName =
Convert.ToString(ConfigurationManager.AppSettings["ReconOutputFileName"]) + "_" +
date;
info = (Path.Combine(HostingEnvironment.ApplicationPhysicalPath,
"ReconExcelData"));
}
else if (DataCategory.ToUpper() == "CALLDETAILS")
{
OutputFileName =
Convert.ToString(ConfigurationManager.AppSettings["CallDetailsOutputFileName"]) +
"_" + date;
info = (Path.Combine(HostingEnvironment.ApplicationPhysicalPath,
"CallDetailsExcelData"));
}

if (!Directory.Exists(info))
{
Directory.CreateDirectory(info);
}

string fileSavePath = Path.Combine(info, OutputFileName) + ".xls";

if (DataCategory.ToUpper() == "RECONCILED")
{
Session["ReconExcelPath"] = fileSavePath;
}
else if (DataCategory.ToUpper() == "CALLDETAILS")
{
Session["CallDetailsExcelPath"] = fileSavePath;
}

try
{
StreamWriter wr = new StreamWriter(fileSavePath, false,
Encoding.Default);

if (DataCategory.ToUpper() == "CALLDETAILS")
{
// Only remove columns if they exist
if (dtToExcel.Columns.Contains("Select"))
dtToExcel.Columns.Remove("Select");

if (dtToExcel.Columns.Contains("Play"))
dtToExcel.Columns.Remove("Play");

if (dtToExcel.Columns.Contains("Download"))
dtToExcel.Columns.Remove("Download");
}

foreach (DataColumn dc in dtToExcel.Columns)


{
wr.Write(dc.ColumnName + "\t");
}
wr.WriteLine();

foreach (DataRow dr in dtToExcel.Rows)


{
string tab = "";
for (int i = 0; i < dtToExcel.Columns.Count; i++)
{
wr.Write(tab + dr[i].ToString());
tab = "\t";
}
wr.WriteLine();
}

// Close file
wr.Close();
}
catch (IOException ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error occurred
while saving file to server in ExportToExcel(). " + ex.Message);
Session["ReconExcelPath"] = "";
Session["CallDetailsExcelPath"] = "";
TempData["CustomError"] = "Please close the file before
uploading.";
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
ExportToExcel()." + ex.Message);
Session["ReconExcelPath"] = "";
Session["CallDetailsExcelPath"] = "";
}
}

public ActionResult LogOut()


{
Session.Clear();
Session.Abandon();
Log.LogMessage(MessageLogger.MessageType.Info, "Logout Successfully.");
return RedirectToAction("Index");
}

public static bool Convertawbtomp3(string source, string target)


{
try
{
string source_filename = source;
string target_filename = target;
if (source_filename != "" && target_filename != "")
{
//cs_ffmpeg_mp3_converter.FFMpeg.Convert2Mp3(source_filename,
target_filename);

return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
Convertawbtomp3()." + ex.Message);
return false;
}

}
public void DeleteTempFolder()
{
try
{
string userName = Convert.ToString(Session["UserID"]);
if (userName != null || userName != "")
{
string userid = Session["UserID"].ToString();
string OutputFileName = "";
string ip = GetIpAddress().ToString();

OutputFileName =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "tempvoicefile", userid,
ip);
string path = OutputFileName + @"\";
if (Directory.Exists(path))
{
Directory.Delete(OutputFileName, true);
//Log.LogMessage(MessageLogger.MessageType.Info, "File
Deleted Successfully :" + OutputFileName);
}

}
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "Error in
DeleteTempFolder()." + ex.Message);
}

public string GetIpAddress()


{
string ip = string.Empty;
try
{
//ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
ip =
System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(',');
string trueIP = ipRange[0].Trim();
}
else
{
ip =
System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

if (ip == "::1" || ip == "127.0.0.1")


{
string hostName =
System.Web.HttpContext.Current.Request.UserHostAddress.ToString();
IPHostEntry entry = Dns.GetHostEntry(hostName);
var ipaddress = entry.AddressList;
foreach (IPAddress ipaddrs in ipaddress)
{
if (ipaddrs.AddressFamily ==
System.Net.Sockets.AddressFamily.InterNetwork)
{
ip = ipaddrs.ToString();
//Log.LogMessage(MessageLogger.MessageType.Info, "IP:"
+ ip);
}
}
}
return ip;
}
catch (Exception ex)
{
Log.LogMessage(MessageLogger.MessageType.Error, "GetIpAddress();" +
"Ip :+'" + ip + "'" + ex.ToString());
return ip;
}

//public string GetUserId(string userName)


//{
// string userid = string.Empty;
// try
// {

// if (userName != "" || userName != null)


// {
// DBConnections =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
// SqlConnection sqlconn = new SqlConnection(DBConnections);
// SqlCommand cmd = new SqlCommand("select a.* from aspnet_Users
a inner join aspnet_Applications b on a.ApplicationId=b.ApplicationId where
a.UserName='" + userName + "' and b.ApplicationName='" + Membership.ApplicationName
+ "'", sqlconn);
// cmd.CommandTimeout = 1000;
// SqlDataAdapter sda = new SqlDataAdapter(cmd);
// DataSet ds = new DataSet();
// sda.Fill(ds);
// userid = ds.Tables[0].Rows[0]["UserId"].ToString();
// }
// else
// {
// Log.LogMessage(MessageLogger.MessageType.Info, "Session
Timeout.");
// }
// return userid;
// }
// catch (Exception ex)
// {

// Log.LogMessage(MessageLogger.MessageType.Error, "GetUserId();" +
ex.ToString());
// return userid;
// }

//}

public int GetGroupByValue()


{
int groupByValue = 0;
DBConnections =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(DBConnections);
SqlCommand cmd = new SqlCommand("select * from tblSettings where
SettingName='GroupBy' and SettingType='CallConfineApplication'", sqlconn);
cmd.CommandTimeout = 1000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
groupByValue = Convert.ToInt32(ds.Tables[0].Rows[0]["SettingValue"]);
return groupByValue;
}

public int CheckAllExtensionAssigned(string userid)


{
int count = 0;
DBConnections =
ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(DBConnections);
SqlCommand cmd = new SqlCommand("select Count(*) AS AssignedCount from
tblAssignedExtension where UserID = '" + userid + "' and AssignedExtension ='ALL'",
sqlconn);
cmd.CommandTimeout = 1000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
count = Convert.ToInt32(ds.Tables[0].Rows[0]["AssignedCount"]);
return count;
}

}
}

You might also like