Web api controller is not sending correct message to Ajax call get











up vote
-3
down vote

favorite












I don't know why api controller is not returning an error message to ajax, it only returns an "" when it should return "Reason codes not maintained"...



This is the response of



query:tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0]; 


in function: GetLastMonthRate. GetLastmonthRate function return the list: lastMonthScrap to function: GenerateReport and GenerateReport should return message;"Reason codes not maintained, please check the list". GenerateReport is called by the Api controller and Api controller is called by Ajax in the Index.



Please help me, I am very new in this language (C#) and I'm about to cry!!!



   public class GlobalScrapController : ApiController
{
[HttpGet]
public String Start(int month,int year)
{
List<clsHistoryScrap> scrapReport = new List<clsHistoryScrap>();
string message = string.Empty;
clsGlobalScrap scrap = new clsGlobalScrap();



message = scrap.GenerateReport(ConfigurationManager.AppSettings["PATH"].ToString(), month, year);

return new JavaScriptSerializer().Serialize(message);
}
}

***************************************************
public string GenerateReport(string path,int month,int year)
{
string message = string.Empty;

if (IsRunning() == false)
{
LogStart(month, "", "#", "0");
FileInfo FileTemplate;

if (month <= 2) FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[0] + ".xlsx");
else FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 2] + ".xlsx");
// if (month <= 2) FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[0] + ".xlsx");//agregado para debuggear //
//else FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[month - 2] + ".xlsx");//agregado para debuggear //
int StartMonthRow = STARTROW + (month * 4); //Define which row we will start updating data base on the month.
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
lastMonthScrap = GetLastMonthRate(year, month); //Get Last Month of Scrap data


/* Message "Reason codes not maintained, please check the list"; */
var listTest = lastMonthScrap.Find(r => r.Msg_RC == "Reason codes not maintained, please check the list");

if (listTest.Msg_RC != "")
{
message = listTest.Msg_RC;
return message; //= "Reason codes not maintained, please check the list";

}
else
{
//If File exists then use current year file, otherwise use Template
if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Reports\Scrap_Template.xlsx");
// if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Scrap_Template.xlsx"); //agregado para debuggear //
using (ExcelPackage pck = new ExcelPackage(FileTemplate, true)) //Open File and allow to update
{
ExcelWorksheet workSheet = pck.Workbook.Worksheets.First();
workSheet.Cells[2, 1].Value = year;
for (int j = 1; j <= tableLiabilities.Rows.Count; j++)
{
workSheet.Cells[HEADERROW, (int)Fields.L1 + (j - 1)].Value = tableLiabilities.Rows[j - 1]["Liability_Name"].ToString() == "-" ? "" : tableLiabilities.Rows[j - 1]["Liability_Name"].ToString();
}
var plants = lastMonthScrap.Select(r => r.Site).Distinct();
int i = 0;
foreach (string plant in plants)
{
var listSelected = lastMonthScrap.Find(r => r.Site == plant);
for (int j = 1; j <= 11; j++)
{
var liability = listSelected.lstLiabilities.Find(x => x.code == "L" + j);
workSheet.Cells[StartMonthRow + i, (int)Fields.L1 + (j - 1)].Value = Double.Parse(liability.value);
}
workSheet.Cells[StartMonthRow + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01;
workSheet.Cells[StartMonthRow + i, (int)Fields.REVENUE].Value = Double.Parse(listSelected.Revenue);
workSheet.Cells[56 + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01; //Grand Total KPI
i++;

}

FileInfo fileNew = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 1] + ".xlsx");
//FileInfo fileNew = new FileInfo(path + "\ScrapReport" + year + Months[month - 1] + ".xlsx");//agregado para debuggear//
pck.SaveAs(fileNew);
}
SaveHistorical(lastMonthScrap, month);
LogStart(month, "../Reports/ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month-1] + " Scrap", "1");
//LogStart(month, "../ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month - 1] + " Scrap", "1");
return "";
} //ELSE - message "Reason codes not maintained, please check the list";
}

return message;



}
**********************************************************************

public List<clsHistoryScrap> GetLastMonthRate(int year, int lastMonth)
{
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
clsHistoryScrap lastMonthScrapSite = new clsHistoryScrap();

string message = string.Empty;

//1. Obtain Historical Data from Database.
string connString = ConfigurationManager.ConnectionStrings["DatabaseScrap"].ConnectionString;
clsOracle database = new clsOracle(connString);
DataTable tableMonthScrap = new DataTable();
DataTable tableRevenue = new DataTable();
DataTable tableRCNotMaintained = new DataTable();
database.Open();
int daysInMonth = DateTime.DaysInMonth(year, lastMonth);
string fields = new string { "inStartMonth", "inEndMonth" };
string values = new string { year + lastMonth.ToString().PadLeft(2,'0') + "01",
year + lastMonth.ToString().PadLeft(2,'0') + daysInMonth};
string fieldRevenue = new string { "inStartMonth", "inEndMonth" };
string fieldRC = new string { "inStartMonth", "inEndMonth" };
// database.callProcedure("PCK_GLOBALSCRAP.SP_DELETEWRONGFILENAME");
tableMonthScrap = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLASTMONTH", fields, values, "outCursor").Tables[0];//Lastmonth's Raw data
tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0];


/* mensaje de "Reason codes not maintained, please check the list"; */
if (tableRCNotMaintained.Rows.Count >= 1)
{

lastMonthScrapSite.Msg_RC = "Reason codes not maintained, please check the list";

lastMonthScrap.Add(lastMonthScrapSite);

return lastMonthScrap;
}
else
{ //*/
tableLiabilities = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLIABILITIES", "outCursor").Tables[0];
tableRevenue = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREVENUE", fieldRevenue, values, "outCursor").Tables[0];
database.Close();
List<clsLiabilityLabels> lastMonthLiabilities = new List<clsLiabilityLabels>();
string _plants = "F912,F136,F522";
//string _plants = "F912,F522,F136";
string plants = _plants.Split(',');
foreach (string plant in plants)
{

lastMonthLiabilities = new List<clsLiabilityLabels>();
foreach (DataRow row in tableLiabilities.Rows) //For each liability
{
string liability = row["LIABILITY_NAME"].ToString();
decimal sum = tableMonthScrap.AsEnumerable()
.Where(r => r.Field<string>("LIABILITY_NAME") == liability && r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("LiabilityValue")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

if (liability == "-")
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = "", value = "0", code = row["LIABILITY_NUMBER"].ToString() });
else
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = liability, value = sum.ToString(), code = row["LIABILITY_NUMBER"].ToString() });
}
decimal revenue = tableRevenue.AsEnumerable()
.Where(r => r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("ShipmentAmount")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

lastMonthScrapSite.KPI = GetKPI().ToString(); //Get KPI Maintained for the month
lastMonthScrapSite.Mes = Months[lastMonth];
lastMonthScrapSite.Ops_Scrap_Percentage = ""; //?
lastMonthScrapSite.Site = ((Sites)int.Parse(plant.Substring(1))).ToString();
lastMonthScrapSite.Total_Scrap = ""; //?
lastMonthScrapSite.TTL_Scrap = ""; //?
lastMonthScrapSite.Werks = plant;
lastMonthScrapSite.Year = year.ToString();
lastMonthScrapSite.lstLiabilities = lastMonthLiabilities;
lastMonthScrapSite.Revenue = revenue.ToString();
//Once Revenue is calculated add to the list.
lastMonthScrap.Add(lastMonthScrapSite);
}
} //else - message "Reason codes not maintained, please check the list";
return lastMonthScrap;
}




function StartJob() {
// clearMessage();
alert('This will take some minutes');
$('#btnStartJob').hide('fast');
var elem = "<i class='fa fa-circle-o-notch fa-spin fa-fw fa-2x'></i>&nbsp;Global Scrap Report is being generated...please wait.";
var d = new Date();
var month = d.getMonth();
var year=d.getFullYear();
if (month == 0) {
month = 12;
year = year - 1;
}
var parameter = { "month": month, "year": year };
$('#divError').hide('fast');
// ajaxCallGet(Link, parameter, '#lblStatus', elem, function (data) { //comentado para debuggear
$.ajax({
url: Link, //dataUrl,
type: "GET",
dataType: "json",
contentType: "application/json",
data: parameter,
beforeSend: function () {
$('#lblStatus').html(elem); // $(element).html(content);
},
success: function (data) {
//Once a response is received we will get the status and files
if (data == "") {
fillTable();
RefreshBaseData();
}
else {
showMessage(data);
$('#lblStatus').html("");
}
$('#btnStartJob').show('fast');
}, // AJAX
error: function (xhr, textStatus, errorThrown) {
// alert(JSON.parse(xhr.responseText).Message);
alert(errorThrown);
} //success: function (data)
});
}









share|improve this question
























  • That's a lot of code. The first thing you need to do is step through it in debug mode and see what happens
    – Nick.McDermaid
    Nov 12 at 0:36










  • I missed the ajax ... :(
    – Eclipse Solar
    Nov 12 at 0:39










  • Put a breakpoint in your action method and debug which lines are getting executed.
    – Shyju
    Nov 12 at 4:08















up vote
-3
down vote

favorite












I don't know why api controller is not returning an error message to ajax, it only returns an "" when it should return "Reason codes not maintained"...



This is the response of



query:tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0]; 


in function: GetLastMonthRate. GetLastmonthRate function return the list: lastMonthScrap to function: GenerateReport and GenerateReport should return message;"Reason codes not maintained, please check the list". GenerateReport is called by the Api controller and Api controller is called by Ajax in the Index.



Please help me, I am very new in this language (C#) and I'm about to cry!!!



   public class GlobalScrapController : ApiController
{
[HttpGet]
public String Start(int month,int year)
{
List<clsHistoryScrap> scrapReport = new List<clsHistoryScrap>();
string message = string.Empty;
clsGlobalScrap scrap = new clsGlobalScrap();



message = scrap.GenerateReport(ConfigurationManager.AppSettings["PATH"].ToString(), month, year);

return new JavaScriptSerializer().Serialize(message);
}
}

***************************************************
public string GenerateReport(string path,int month,int year)
{
string message = string.Empty;

if (IsRunning() == false)
{
LogStart(month, "", "#", "0");
FileInfo FileTemplate;

if (month <= 2) FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[0] + ".xlsx");
else FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 2] + ".xlsx");
// if (month <= 2) FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[0] + ".xlsx");//agregado para debuggear //
//else FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[month - 2] + ".xlsx");//agregado para debuggear //
int StartMonthRow = STARTROW + (month * 4); //Define which row we will start updating data base on the month.
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
lastMonthScrap = GetLastMonthRate(year, month); //Get Last Month of Scrap data


/* Message "Reason codes not maintained, please check the list"; */
var listTest = lastMonthScrap.Find(r => r.Msg_RC == "Reason codes not maintained, please check the list");

if (listTest.Msg_RC != "")
{
message = listTest.Msg_RC;
return message; //= "Reason codes not maintained, please check the list";

}
else
{
//If File exists then use current year file, otherwise use Template
if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Reports\Scrap_Template.xlsx");
// if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Scrap_Template.xlsx"); //agregado para debuggear //
using (ExcelPackage pck = new ExcelPackage(FileTemplate, true)) //Open File and allow to update
{
ExcelWorksheet workSheet = pck.Workbook.Worksheets.First();
workSheet.Cells[2, 1].Value = year;
for (int j = 1; j <= tableLiabilities.Rows.Count; j++)
{
workSheet.Cells[HEADERROW, (int)Fields.L1 + (j - 1)].Value = tableLiabilities.Rows[j - 1]["Liability_Name"].ToString() == "-" ? "" : tableLiabilities.Rows[j - 1]["Liability_Name"].ToString();
}
var plants = lastMonthScrap.Select(r => r.Site).Distinct();
int i = 0;
foreach (string plant in plants)
{
var listSelected = lastMonthScrap.Find(r => r.Site == plant);
for (int j = 1; j <= 11; j++)
{
var liability = listSelected.lstLiabilities.Find(x => x.code == "L" + j);
workSheet.Cells[StartMonthRow + i, (int)Fields.L1 + (j - 1)].Value = Double.Parse(liability.value);
}
workSheet.Cells[StartMonthRow + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01;
workSheet.Cells[StartMonthRow + i, (int)Fields.REVENUE].Value = Double.Parse(listSelected.Revenue);
workSheet.Cells[56 + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01; //Grand Total KPI
i++;

}

FileInfo fileNew = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 1] + ".xlsx");
//FileInfo fileNew = new FileInfo(path + "\ScrapReport" + year + Months[month - 1] + ".xlsx");//agregado para debuggear//
pck.SaveAs(fileNew);
}
SaveHistorical(lastMonthScrap, month);
LogStart(month, "../Reports/ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month-1] + " Scrap", "1");
//LogStart(month, "../ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month - 1] + " Scrap", "1");
return "";
} //ELSE - message "Reason codes not maintained, please check the list";
}

return message;



}
**********************************************************************

public List<clsHistoryScrap> GetLastMonthRate(int year, int lastMonth)
{
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
clsHistoryScrap lastMonthScrapSite = new clsHistoryScrap();

string message = string.Empty;

//1. Obtain Historical Data from Database.
string connString = ConfigurationManager.ConnectionStrings["DatabaseScrap"].ConnectionString;
clsOracle database = new clsOracle(connString);
DataTable tableMonthScrap = new DataTable();
DataTable tableRevenue = new DataTable();
DataTable tableRCNotMaintained = new DataTable();
database.Open();
int daysInMonth = DateTime.DaysInMonth(year, lastMonth);
string fields = new string { "inStartMonth", "inEndMonth" };
string values = new string { year + lastMonth.ToString().PadLeft(2,'0') + "01",
year + lastMonth.ToString().PadLeft(2,'0') + daysInMonth};
string fieldRevenue = new string { "inStartMonth", "inEndMonth" };
string fieldRC = new string { "inStartMonth", "inEndMonth" };
// database.callProcedure("PCK_GLOBALSCRAP.SP_DELETEWRONGFILENAME");
tableMonthScrap = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLASTMONTH", fields, values, "outCursor").Tables[0];//Lastmonth's Raw data
tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0];


/* mensaje de "Reason codes not maintained, please check the list"; */
if (tableRCNotMaintained.Rows.Count >= 1)
{

lastMonthScrapSite.Msg_RC = "Reason codes not maintained, please check the list";

lastMonthScrap.Add(lastMonthScrapSite);

return lastMonthScrap;
}
else
{ //*/
tableLiabilities = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLIABILITIES", "outCursor").Tables[0];
tableRevenue = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREVENUE", fieldRevenue, values, "outCursor").Tables[0];
database.Close();
List<clsLiabilityLabels> lastMonthLiabilities = new List<clsLiabilityLabels>();
string _plants = "F912,F136,F522";
//string _plants = "F912,F522,F136";
string plants = _plants.Split(',');
foreach (string plant in plants)
{

lastMonthLiabilities = new List<clsLiabilityLabels>();
foreach (DataRow row in tableLiabilities.Rows) //For each liability
{
string liability = row["LIABILITY_NAME"].ToString();
decimal sum = tableMonthScrap.AsEnumerable()
.Where(r => r.Field<string>("LIABILITY_NAME") == liability && r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("LiabilityValue")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

if (liability == "-")
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = "", value = "0", code = row["LIABILITY_NUMBER"].ToString() });
else
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = liability, value = sum.ToString(), code = row["LIABILITY_NUMBER"].ToString() });
}
decimal revenue = tableRevenue.AsEnumerable()
.Where(r => r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("ShipmentAmount")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

lastMonthScrapSite.KPI = GetKPI().ToString(); //Get KPI Maintained for the month
lastMonthScrapSite.Mes = Months[lastMonth];
lastMonthScrapSite.Ops_Scrap_Percentage = ""; //?
lastMonthScrapSite.Site = ((Sites)int.Parse(plant.Substring(1))).ToString();
lastMonthScrapSite.Total_Scrap = ""; //?
lastMonthScrapSite.TTL_Scrap = ""; //?
lastMonthScrapSite.Werks = plant;
lastMonthScrapSite.Year = year.ToString();
lastMonthScrapSite.lstLiabilities = lastMonthLiabilities;
lastMonthScrapSite.Revenue = revenue.ToString();
//Once Revenue is calculated add to the list.
lastMonthScrap.Add(lastMonthScrapSite);
}
} //else - message "Reason codes not maintained, please check the list";
return lastMonthScrap;
}




function StartJob() {
// clearMessage();
alert('This will take some minutes');
$('#btnStartJob').hide('fast');
var elem = "<i class='fa fa-circle-o-notch fa-spin fa-fw fa-2x'></i>&nbsp;Global Scrap Report is being generated...please wait.";
var d = new Date();
var month = d.getMonth();
var year=d.getFullYear();
if (month == 0) {
month = 12;
year = year - 1;
}
var parameter = { "month": month, "year": year };
$('#divError').hide('fast');
// ajaxCallGet(Link, parameter, '#lblStatus', elem, function (data) { //comentado para debuggear
$.ajax({
url: Link, //dataUrl,
type: "GET",
dataType: "json",
contentType: "application/json",
data: parameter,
beforeSend: function () {
$('#lblStatus').html(elem); // $(element).html(content);
},
success: function (data) {
//Once a response is received we will get the status and files
if (data == "") {
fillTable();
RefreshBaseData();
}
else {
showMessage(data);
$('#lblStatus').html("");
}
$('#btnStartJob').show('fast');
}, // AJAX
error: function (xhr, textStatus, errorThrown) {
// alert(JSON.parse(xhr.responseText).Message);
alert(errorThrown);
} //success: function (data)
});
}









share|improve this question
























  • That's a lot of code. The first thing you need to do is step through it in debug mode and see what happens
    – Nick.McDermaid
    Nov 12 at 0:36










  • I missed the ajax ... :(
    – Eclipse Solar
    Nov 12 at 0:39










  • Put a breakpoint in your action method and debug which lines are getting executed.
    – Shyju
    Nov 12 at 4:08













up vote
-3
down vote

favorite









up vote
-3
down vote

favorite











I don't know why api controller is not returning an error message to ajax, it only returns an "" when it should return "Reason codes not maintained"...



This is the response of



query:tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0]; 


in function: GetLastMonthRate. GetLastmonthRate function return the list: lastMonthScrap to function: GenerateReport and GenerateReport should return message;"Reason codes not maintained, please check the list". GenerateReport is called by the Api controller and Api controller is called by Ajax in the Index.



Please help me, I am very new in this language (C#) and I'm about to cry!!!



   public class GlobalScrapController : ApiController
{
[HttpGet]
public String Start(int month,int year)
{
List<clsHistoryScrap> scrapReport = new List<clsHistoryScrap>();
string message = string.Empty;
clsGlobalScrap scrap = new clsGlobalScrap();



message = scrap.GenerateReport(ConfigurationManager.AppSettings["PATH"].ToString(), month, year);

return new JavaScriptSerializer().Serialize(message);
}
}

***************************************************
public string GenerateReport(string path,int month,int year)
{
string message = string.Empty;

if (IsRunning() == false)
{
LogStart(month, "", "#", "0");
FileInfo FileTemplate;

if (month <= 2) FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[0] + ".xlsx");
else FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 2] + ".xlsx");
// if (month <= 2) FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[0] + ".xlsx");//agregado para debuggear //
//else FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[month - 2] + ".xlsx");//agregado para debuggear //
int StartMonthRow = STARTROW + (month * 4); //Define which row we will start updating data base on the month.
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
lastMonthScrap = GetLastMonthRate(year, month); //Get Last Month of Scrap data


/* Message "Reason codes not maintained, please check the list"; */
var listTest = lastMonthScrap.Find(r => r.Msg_RC == "Reason codes not maintained, please check the list");

if (listTest.Msg_RC != "")
{
message = listTest.Msg_RC;
return message; //= "Reason codes not maintained, please check the list";

}
else
{
//If File exists then use current year file, otherwise use Template
if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Reports\Scrap_Template.xlsx");
// if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Scrap_Template.xlsx"); //agregado para debuggear //
using (ExcelPackage pck = new ExcelPackage(FileTemplate, true)) //Open File and allow to update
{
ExcelWorksheet workSheet = pck.Workbook.Worksheets.First();
workSheet.Cells[2, 1].Value = year;
for (int j = 1; j <= tableLiabilities.Rows.Count; j++)
{
workSheet.Cells[HEADERROW, (int)Fields.L1 + (j - 1)].Value = tableLiabilities.Rows[j - 1]["Liability_Name"].ToString() == "-" ? "" : tableLiabilities.Rows[j - 1]["Liability_Name"].ToString();
}
var plants = lastMonthScrap.Select(r => r.Site).Distinct();
int i = 0;
foreach (string plant in plants)
{
var listSelected = lastMonthScrap.Find(r => r.Site == plant);
for (int j = 1; j <= 11; j++)
{
var liability = listSelected.lstLiabilities.Find(x => x.code == "L" + j);
workSheet.Cells[StartMonthRow + i, (int)Fields.L1 + (j - 1)].Value = Double.Parse(liability.value);
}
workSheet.Cells[StartMonthRow + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01;
workSheet.Cells[StartMonthRow + i, (int)Fields.REVENUE].Value = Double.Parse(listSelected.Revenue);
workSheet.Cells[56 + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01; //Grand Total KPI
i++;

}

FileInfo fileNew = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 1] + ".xlsx");
//FileInfo fileNew = new FileInfo(path + "\ScrapReport" + year + Months[month - 1] + ".xlsx");//agregado para debuggear//
pck.SaveAs(fileNew);
}
SaveHistorical(lastMonthScrap, month);
LogStart(month, "../Reports/ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month-1] + " Scrap", "1");
//LogStart(month, "../ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month - 1] + " Scrap", "1");
return "";
} //ELSE - message "Reason codes not maintained, please check the list";
}

return message;



}
**********************************************************************

public List<clsHistoryScrap> GetLastMonthRate(int year, int lastMonth)
{
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
clsHistoryScrap lastMonthScrapSite = new clsHistoryScrap();

string message = string.Empty;

//1. Obtain Historical Data from Database.
string connString = ConfigurationManager.ConnectionStrings["DatabaseScrap"].ConnectionString;
clsOracle database = new clsOracle(connString);
DataTable tableMonthScrap = new DataTable();
DataTable tableRevenue = new DataTable();
DataTable tableRCNotMaintained = new DataTable();
database.Open();
int daysInMonth = DateTime.DaysInMonth(year, lastMonth);
string fields = new string { "inStartMonth", "inEndMonth" };
string values = new string { year + lastMonth.ToString().PadLeft(2,'0') + "01",
year + lastMonth.ToString().PadLeft(2,'0') + daysInMonth};
string fieldRevenue = new string { "inStartMonth", "inEndMonth" };
string fieldRC = new string { "inStartMonth", "inEndMonth" };
// database.callProcedure("PCK_GLOBALSCRAP.SP_DELETEWRONGFILENAME");
tableMonthScrap = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLASTMONTH", fields, values, "outCursor").Tables[0];//Lastmonth's Raw data
tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0];


/* mensaje de "Reason codes not maintained, please check the list"; */
if (tableRCNotMaintained.Rows.Count >= 1)
{

lastMonthScrapSite.Msg_RC = "Reason codes not maintained, please check the list";

lastMonthScrap.Add(lastMonthScrapSite);

return lastMonthScrap;
}
else
{ //*/
tableLiabilities = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLIABILITIES", "outCursor").Tables[0];
tableRevenue = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREVENUE", fieldRevenue, values, "outCursor").Tables[0];
database.Close();
List<clsLiabilityLabels> lastMonthLiabilities = new List<clsLiabilityLabels>();
string _plants = "F912,F136,F522";
//string _plants = "F912,F522,F136";
string plants = _plants.Split(',');
foreach (string plant in plants)
{

lastMonthLiabilities = new List<clsLiabilityLabels>();
foreach (DataRow row in tableLiabilities.Rows) //For each liability
{
string liability = row["LIABILITY_NAME"].ToString();
decimal sum = tableMonthScrap.AsEnumerable()
.Where(r => r.Field<string>("LIABILITY_NAME") == liability && r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("LiabilityValue")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

if (liability == "-")
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = "", value = "0", code = row["LIABILITY_NUMBER"].ToString() });
else
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = liability, value = sum.ToString(), code = row["LIABILITY_NUMBER"].ToString() });
}
decimal revenue = tableRevenue.AsEnumerable()
.Where(r => r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("ShipmentAmount")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

lastMonthScrapSite.KPI = GetKPI().ToString(); //Get KPI Maintained for the month
lastMonthScrapSite.Mes = Months[lastMonth];
lastMonthScrapSite.Ops_Scrap_Percentage = ""; //?
lastMonthScrapSite.Site = ((Sites)int.Parse(plant.Substring(1))).ToString();
lastMonthScrapSite.Total_Scrap = ""; //?
lastMonthScrapSite.TTL_Scrap = ""; //?
lastMonthScrapSite.Werks = plant;
lastMonthScrapSite.Year = year.ToString();
lastMonthScrapSite.lstLiabilities = lastMonthLiabilities;
lastMonthScrapSite.Revenue = revenue.ToString();
//Once Revenue is calculated add to the list.
lastMonthScrap.Add(lastMonthScrapSite);
}
} //else - message "Reason codes not maintained, please check the list";
return lastMonthScrap;
}




function StartJob() {
// clearMessage();
alert('This will take some minutes');
$('#btnStartJob').hide('fast');
var elem = "<i class='fa fa-circle-o-notch fa-spin fa-fw fa-2x'></i>&nbsp;Global Scrap Report is being generated...please wait.";
var d = new Date();
var month = d.getMonth();
var year=d.getFullYear();
if (month == 0) {
month = 12;
year = year - 1;
}
var parameter = { "month": month, "year": year };
$('#divError').hide('fast');
// ajaxCallGet(Link, parameter, '#lblStatus', elem, function (data) { //comentado para debuggear
$.ajax({
url: Link, //dataUrl,
type: "GET",
dataType: "json",
contentType: "application/json",
data: parameter,
beforeSend: function () {
$('#lblStatus').html(elem); // $(element).html(content);
},
success: function (data) {
//Once a response is received we will get the status and files
if (data == "") {
fillTable();
RefreshBaseData();
}
else {
showMessage(data);
$('#lblStatus').html("");
}
$('#btnStartJob').show('fast');
}, // AJAX
error: function (xhr, textStatus, errorThrown) {
// alert(JSON.parse(xhr.responseText).Message);
alert(errorThrown);
} //success: function (data)
});
}









share|improve this question















I don't know why api controller is not returning an error message to ajax, it only returns an "" when it should return "Reason codes not maintained"...



This is the response of



query:tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0]; 


in function: GetLastMonthRate. GetLastmonthRate function return the list: lastMonthScrap to function: GenerateReport and GenerateReport should return message;"Reason codes not maintained, please check the list". GenerateReport is called by the Api controller and Api controller is called by Ajax in the Index.



Please help me, I am very new in this language (C#) and I'm about to cry!!!



   public class GlobalScrapController : ApiController
{
[HttpGet]
public String Start(int month,int year)
{
List<clsHistoryScrap> scrapReport = new List<clsHistoryScrap>();
string message = string.Empty;
clsGlobalScrap scrap = new clsGlobalScrap();



message = scrap.GenerateReport(ConfigurationManager.AppSettings["PATH"].ToString(), month, year);

return new JavaScriptSerializer().Serialize(message);
}
}

***************************************************
public string GenerateReport(string path,int month,int year)
{
string message = string.Empty;

if (IsRunning() == false)
{
LogStart(month, "", "#", "0");
FileInfo FileTemplate;

if (month <= 2) FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[0] + ".xlsx");
else FileTemplate = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 2] + ".xlsx");
// if (month <= 2) FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[0] + ".xlsx");//agregado para debuggear //
//else FileTemplate = new FileInfo(path + "\ScrapReport" + year + Months[month - 2] + ".xlsx");//agregado para debuggear //
int StartMonthRow = STARTROW + (month * 4); //Define which row we will start updating data base on the month.
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
lastMonthScrap = GetLastMonthRate(year, month); //Get Last Month of Scrap data


/* Message "Reason codes not maintained, please check the list"; */
var listTest = lastMonthScrap.Find(r => r.Msg_RC == "Reason codes not maintained, please check the list");

if (listTest.Msg_RC != "")
{
message = listTest.Msg_RC;
return message; //= "Reason codes not maintained, please check the list";

}
else
{
//If File exists then use current year file, otherwise use Template
if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Reports\Scrap_Template.xlsx");
// if (FileTemplate.Exists == false) FileTemplate = new FileInfo(path + "\Scrap_Template.xlsx"); //agregado para debuggear //
using (ExcelPackage pck = new ExcelPackage(FileTemplate, true)) //Open File and allow to update
{
ExcelWorksheet workSheet = pck.Workbook.Worksheets.First();
workSheet.Cells[2, 1].Value = year;
for (int j = 1; j <= tableLiabilities.Rows.Count; j++)
{
workSheet.Cells[HEADERROW, (int)Fields.L1 + (j - 1)].Value = tableLiabilities.Rows[j - 1]["Liability_Name"].ToString() == "-" ? "" : tableLiabilities.Rows[j - 1]["Liability_Name"].ToString();
}
var plants = lastMonthScrap.Select(r => r.Site).Distinct();
int i = 0;
foreach (string plant in plants)
{
var listSelected = lastMonthScrap.Find(r => r.Site == plant);
for (int j = 1; j <= 11; j++)
{
var liability = listSelected.lstLiabilities.Find(x => x.code == "L" + j);
workSheet.Cells[StartMonthRow + i, (int)Fields.L1 + (j - 1)].Value = Double.Parse(liability.value);
}
workSheet.Cells[StartMonthRow + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01;
workSheet.Cells[StartMonthRow + i, (int)Fields.REVENUE].Value = Double.Parse(listSelected.Revenue);
workSheet.Cells[56 + i, (int)Fields.KPI].Value = Double.Parse(listSelected.KPI) * .01; //Grand Total KPI
i++;

}

FileInfo fileNew = new FileInfo(path + "\Reports\ScrapReport" + year + Months[month - 1] + ".xlsx");
//FileInfo fileNew = new FileInfo(path + "\ScrapReport" + year + Months[month - 1] + ".xlsx");//agregado para debuggear//
pck.SaveAs(fileNew);
}
SaveHistorical(lastMonthScrap, month);
LogStart(month, "../Reports/ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month-1] + " Scrap", "1");
//LogStart(month, "../ScrapReport" + year + Months[month - 1] + ".xlsx", Months[month - 1] + " Scrap", "1");
return "";
} //ELSE - message "Reason codes not maintained, please check the list";
}

return message;



}
**********************************************************************

public List<clsHistoryScrap> GetLastMonthRate(int year, int lastMonth)
{
List<clsHistoryScrap> lastMonthScrap = new List<clsHistoryScrap>();
clsHistoryScrap lastMonthScrapSite = new clsHistoryScrap();

string message = string.Empty;

//1. Obtain Historical Data from Database.
string connString = ConfigurationManager.ConnectionStrings["DatabaseScrap"].ConnectionString;
clsOracle database = new clsOracle(connString);
DataTable tableMonthScrap = new DataTable();
DataTable tableRevenue = new DataTable();
DataTable tableRCNotMaintained = new DataTable();
database.Open();
int daysInMonth = DateTime.DaysInMonth(year, lastMonth);
string fields = new string { "inStartMonth", "inEndMonth" };
string values = new string { year + lastMonth.ToString().PadLeft(2,'0') + "01",
year + lastMonth.ToString().PadLeft(2,'0') + daysInMonth};
string fieldRevenue = new string { "inStartMonth", "inEndMonth" };
string fieldRC = new string { "inStartMonth", "inEndMonth" };
// database.callProcedure("PCK_GLOBALSCRAP.SP_DELETEWRONGFILENAME");
tableMonthScrap = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLASTMONTH", fields, values, "outCursor").Tables[0];//Lastmonth's Raw data
tableRCNotMaintained = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREASONCODESNOTMAINTAINED", fieldRC, values, "outCursor").Tables[0];


/* mensaje de "Reason codes not maintained, please check the list"; */
if (tableRCNotMaintained.Rows.Count >= 1)
{

lastMonthScrapSite.Msg_RC = "Reason codes not maintained, please check the list";

lastMonthScrap.Add(lastMonthScrapSite);

return lastMonthScrap;
}
else
{ //*/
tableLiabilities = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETLIABILITIES", "outCursor").Tables[0];
tableRevenue = database.FillDataTable("PCK_GLOBALSCRAP.SP_GETREVENUE", fieldRevenue, values, "outCursor").Tables[0];
database.Close();
List<clsLiabilityLabels> lastMonthLiabilities = new List<clsLiabilityLabels>();
string _plants = "F912,F136,F522";
//string _plants = "F912,F522,F136";
string plants = _plants.Split(',');
foreach (string plant in plants)
{

lastMonthLiabilities = new List<clsLiabilityLabels>();
foreach (DataRow row in tableLiabilities.Rows) //For each liability
{
string liability = row["LIABILITY_NAME"].ToString();
decimal sum = tableMonthScrap.AsEnumerable()
.Where(r => r.Field<string>("LIABILITY_NAME") == liability && r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("LiabilityValue")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

if (liability == "-")
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = "", value = "0", code = row["LIABILITY_NUMBER"].ToString() });
else
lastMonthLiabilities.Add(new clsLiabilityLabels() { description = liability, value = sum.ToString(), code = row["LIABILITY_NUMBER"].ToString() });
}
decimal revenue = tableRevenue.AsEnumerable()
.Where(r => r.Field<string>("plant_from") == plant)
.Sum(r => r.Field<decimal>("ShipmentAmount")); //Total Value (Value must be multiplied by Std Cost and conversion rate applied) by Liability

lastMonthScrapSite.KPI = GetKPI().ToString(); //Get KPI Maintained for the month
lastMonthScrapSite.Mes = Months[lastMonth];
lastMonthScrapSite.Ops_Scrap_Percentage = ""; //?
lastMonthScrapSite.Site = ((Sites)int.Parse(plant.Substring(1))).ToString();
lastMonthScrapSite.Total_Scrap = ""; //?
lastMonthScrapSite.TTL_Scrap = ""; //?
lastMonthScrapSite.Werks = plant;
lastMonthScrapSite.Year = year.ToString();
lastMonthScrapSite.lstLiabilities = lastMonthLiabilities;
lastMonthScrapSite.Revenue = revenue.ToString();
//Once Revenue is calculated add to the list.
lastMonthScrap.Add(lastMonthScrapSite);
}
} //else - message "Reason codes not maintained, please check the list";
return lastMonthScrap;
}




function StartJob() {
// clearMessage();
alert('This will take some minutes');
$('#btnStartJob').hide('fast');
var elem = "<i class='fa fa-circle-o-notch fa-spin fa-fw fa-2x'></i>&nbsp;Global Scrap Report is being generated...please wait.";
var d = new Date();
var month = d.getMonth();
var year=d.getFullYear();
if (month == 0) {
month = 12;
year = year - 1;
}
var parameter = { "month": month, "year": year };
$('#divError').hide('fast');
// ajaxCallGet(Link, parameter, '#lblStatus', elem, function (data) { //comentado para debuggear
$.ajax({
url: Link, //dataUrl,
type: "GET",
dataType: "json",
contentType: "application/json",
data: parameter,
beforeSend: function () {
$('#lblStatus').html(elem); // $(element).html(content);
},
success: function (data) {
//Once a response is received we will get the status and files
if (data == "") {
fillTable();
RefreshBaseData();
}
else {
showMessage(data);
$('#lblStatus').html("");
}
$('#btnStartJob').show('fast');
}, // AJAX
error: function (xhr, textStatus, errorThrown) {
// alert(JSON.parse(xhr.responseText).Message);
alert(errorThrown);
} //success: function (data)
});
}






asp.net-web-api model-view-controller






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 at 21:43









marc_s

568k12810991249




568k12810991249










asked Nov 12 at 0:31









Eclipse Solar

11




11












  • That's a lot of code. The first thing you need to do is step through it in debug mode and see what happens
    – Nick.McDermaid
    Nov 12 at 0:36










  • I missed the ajax ... :(
    – Eclipse Solar
    Nov 12 at 0:39










  • Put a breakpoint in your action method and debug which lines are getting executed.
    – Shyju
    Nov 12 at 4:08


















  • That's a lot of code. The first thing you need to do is step through it in debug mode and see what happens
    – Nick.McDermaid
    Nov 12 at 0:36










  • I missed the ajax ... :(
    – Eclipse Solar
    Nov 12 at 0:39










  • Put a breakpoint in your action method and debug which lines are getting executed.
    – Shyju
    Nov 12 at 4:08
















That's a lot of code. The first thing you need to do is step through it in debug mode and see what happens
– Nick.McDermaid
Nov 12 at 0:36




That's a lot of code. The first thing you need to do is step through it in debug mode and see what happens
– Nick.McDermaid
Nov 12 at 0:36












I missed the ajax ... :(
– Eclipse Solar
Nov 12 at 0:39




I missed the ajax ... :(
– Eclipse Solar
Nov 12 at 0:39












Put a breakpoint in your action method and debug which lines are getting executed.
– Shyju
Nov 12 at 4:08




Put a breakpoint in your action method and debug which lines are getting executed.
– Shyju
Nov 12 at 4:08

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254631%2fweb-api-controller-is-not-sending-correct-message-to-ajax-call-get%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254631%2fweb-api-controller-is-not-sending-correct-message-to-ajax-call-get%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine