IIS connections overload and CPU running high - javascript

We have an MVC 5 website hosted by iis on our server but we are experiencing the following problem with one of the functionalities in the website.
We have a datatable that gets populated with data from a SQL database. For each record a checkbox gets created for users to check and link that record. Once the record is checked and linked, that specific record is stored in a link table. Please see the code bellow for this functionality. For each record I call a method on the server side and that executes the stored proc.
javascript
$("#btnLinkTest").click(function () {
var counter = 0;
var checked_checkboxCounter = 0;
$('#counter').text("0 linked");
$('#linkModal').modal('show');
var oTable = $("#StudentListTable").dataTable();
$(".cbxLink:checked", oTable.fnGetNodes()).each(function () {
checked_checkboxCounter = checked_checkboxCounter + 1;
var currentRow = $(this).closest("tr");
var data = $('#StudentListTable').DataTable().row(currentRow).data();
var ER, AC;
var StudentID = data['StudentID'];
var TestID = $('#lblGradeID').html();
var ET = $(this).closest('tr').find(".extraTime").val();
if ($(this).closest('tr').find(".cbxER").is(':checked')) {
ER = "True";
} else {
ER = "False";
}
if ($(this).closest('tr').find(".cbxAC").is(':checked')) {
AC = "True";
} else {
AC = "False";
}
var jsObject =
{
StudentID: StudentID,
TestID: TestID,
ModifiedBy: "1",
ElectronicReader: ER,
Accomodation: AC,
StudentExtraTime: ET
};
$.ajax({
type: "POST",
url: "/Administration/LinkTestToStudent_Ins/",
data: JSON.stringify(jsObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
counter = counter + 1;
$('#counter').text(counter + " / " + checked_checkboxCounter );
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
return false;
});
c#
public string LinkTestToStudent_Ins(string StudentID, string TestID, string ModifiedBy, string ElectronicReader, string Accomodation, string StudentExtraTime)
{
string result;
DataBaseConnection dbConn = new DataBaseConnection();
using (SqlConnection con = dbConn.SqlConn())
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("StudentTestLink_ins", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StudentID", StudentID);
cmd.Parameters.AddWithValue("#TestID", TestID);
cmd.Parameters.AddWithValue("#ModifiedBy", HttpContext.Current.Session["UserID"]);
cmd.ExecuteNonQuery();
con.Close();
return result = "Linked";
}
catch (Exception ex)
{
return "Connection Error";
}
}
}
The problem is if we link over a 100 records for example, the connections on the server goes up a lot (so 100 in this case) and the cpu runs at almost 100% because of the IIS Worker. I suspect that this is happening because the javascript code calls the c# all at once for all checked records.
Please advise how I can optimize this code so that I do not get the above mentioned problem. Possibly I can call the c# method one at a time and not all at once.

Related

How To Call Json API from C# Useing Javascript

I made this Web API Apllication Using ASP.NET und C#
and output response from this API is Json object To can in java script Application Call this API with Ajax
this is C# Code :
public string Get()
{
string Sql3 = "(SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song,Speaker_Volume,Speaker_Availability, Speaker_Mute,Date_Time,Speaker_Status, Row_Number() over (order by Date_Time desc) as RowNumber FROM Raspi_speaker)T";
string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";
string Sql = "SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song," + Sql2 + Sql3;
SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
string[] Result = new string[10];
DataTable dataTable = new DataTable();
adap.Fill(dataTable);
int i = 0;
foreach (DataRow dataR in dataTable.Rows)
{
string Val;
Val = Convert.ToString(dataR["Raspberry_name"]);
Result[i] = Val;
i++;
}
Object[] obj = {
new { RasspiName = Result}
};
if (dataTable.Rows.Count > 0)
{
return JsonConvert.SerializeObject(obj);
}
return "No Data Found";
}
}
and output is this Json Object:
[{"RasspiName":["Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Trais-Sonos-Pi","Trais-Sonos-Pi","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS"]}]
JavaScript Code is:
function Ajax(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4 && (request.status == 200)) {
var DataR = [];
DataR =JSON.parse(request.responseText)
console.log(DataR)
}
}
var url = 'http://localhost:41839/api/Musik';
request.open('GET',url ,true);
request.send()
}
My problem is that it treats the Json object as text Although I used ((JSON.parse)) Method in Java Script ... For example when I write (( console.log(DataR[ 0 ])) I get only one Letter for Example [ Instead of Value when I write (( console.log(DataR[ 0 ].RasspiName)) I get Undefined
I dont know if proplem from C# code oder From Java Script
I hope your help thanks so much
I don't understand how you defined the API Get method in the back-end code example, but I think you should set something like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDashboardInfo()
{
//your code here
}
You can use Ajax to make the GET request:
function GetData() {
try {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:41839/api/Musik",
data: '',
dataType: "json",
success: OnSuccessGetData,
error: OnErrorGetData
});
}
catch (ex) {
console.log("GetData(): " + ex.toString());
}
}
function OnSuccessGetData(result) {
try {
if (result.d !== "" && result.d !== null) {
var dataSourceJson = JSON.parse(result.d);
}
else {
console.log("OnSuccessGetData: result is null!");
}
}
catch (ex) {
console.log("OnSuccessGetData(): " + ex.toString());
}
}
function OnErrorGetData(httpRequest, textStatus, errorThrown) {
try {
console.log("OnErrorGetDashboardData: " + textStatus + " " + errorThrown + " " + httpRequest);
}
catch (ex) {
console.log("OnErrorGetDashboardData(): " + ex.toString());
}
}
More about JavaScript Get request here.

Authorization issues with Ajax

I ran into a problem with Ajax: i am calling a server side function via Ajax. Nothing strange so far. The problem is that it doesn't give me back any results and while debugging, I found that it gives permission problems. I don't understand where the problem is.
CODICE AJAX
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
let parametri = { utente: user, Password: pass }
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebControls.aspx/CliccaBottone",
data: JSON.stringify(parametri),
dataType: "json",
success: function (i) {
if (i == 0) {
alert("Le credenziali sono errate");
}
else {
alert("Hai eseguito il login");
}
}
});
CODICE C#
public partial class WebControls : System.Web.UI.Page
{
[WebMethod(EnableSession = true)]
public static int CliccaBottone(string utente, string Password)
{
string queryString = "SELECT * FROM Credenziali WHERE Username = #User AND Pass = #Password";
int i = 0;
//VIENE APERTA LA CONNESSIONE COL DB
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["coso"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
SqlParameter parameter = new SqlParameter("User", utente);
SqlParameter parameter2 = new SqlParameter("Password", Password);
command.Parameters.Add(parameter);
command.Parameters.Add(parameter2);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
i++;
}
reader.Close();
}
}
return i;
}
}
}
I suspect there is an error on the server side, because the syntax written on the client side seems correct to me. But logically if an incorrect function is called that will not work. Thank you very much for helping.
How are you handling credentials when connecting the the database itself? If it's pass through authentication, what credentials is your application using when accessing the database?

Works perfect locally but on server: Failed to load resource: 500 (Internal Server Error)

I have a MVC5 web application which i have been working for a while. When i work on local it works perfect. But when i publish it to our company server, in a section where i print a receipt im having "Failed to load resource" error. As I said it works perfect when im working on local. Im using devexpress xtrareport .print() method to print the receipt. Here are some codes that im using:
POST method, this is the view where i get the error:
function result() {
$(document).ready(function () {
value = document.getElementById('tutar').value;
var value3 = document.getElementById('bankalar').value;
var value2 = parseFloat(value);
try {
value1 = document.getElementById('1001').innerHTML;
} catch {
value1 = "Girilmedi";
}
if (document.getElementById("musteriAdi0").value == "") {
alert("Müşteri Adı Girilmeden İşlem Yapılamaz");
for (var u = p; u < i; u++) {
try {
var element = document.getElementById(u);
var row = element.parentNode.parentNode;
row.parentNode.removeChild(row);
} catch {
}
}
window.location.href = '#Url.Action("HizliAlimSatim", "Kuyumcu")';
}
else {
ekle();
var m = JSON.stringify({
'model': things, 'toplam': value2, 'personel': value1, 'KrediKarti': value3
});
things = [];
$(function () {
$.ajax({
type: "POST",
url: "/Kuyumcu/HizliAlimSatim",
contentType: "application/json; charset=utf-8",
dataType: "Json",
data: m,
success: function (data) {
if (data.includes("/Kuyumcu/Document") == false) {
g = g - i;
} else {
alert("İşlem Başarılı!");
//window.open(data, '_blank');
document.getElementById('tutar').value = 0;
toplam = 0;
degistir();
for (var u = p; u < i; u++) {
try {
var element = document.getElementById(u);
var row = element.parentNode.parentNode;
row.parentNode.removeChild(row);
} catch {
}
}
p = i;
window.location.reload(true);
}
}
});
});
}
});
}
this is the controller where i call print method:
Fis report = new Fis();
report.Parameters["FisNo"].Value = id;
report.Parameters["Musteri"].Value = model[0].MusteriAdSoyad;
report.Parameters["Islemci"].Value = personel;
report.CreateDocument(false);
//report.ShowPreview();
report.PrintingSystem.ShowMarginsWarning = false;
report.Print();
return Json(Url.Action("Document", "Kuyumcu");
I have been trying to solve the issue for 2 days, I thought its a server side problem but whatever i changed it didnt work.
The XtraReport.Print method from your controller is invoked at the server side - that's why it works when you run your application on localhost. When you deploy it to the production server, the Print method will be executed at the server's machine - not the client one.
Assuming that you use a DocumentViewer to display a report on your web page, use the viewer's client-side API (see the Print method) to print a report. For instance, refer to the sample code snippet from the How to display print dialog after the WebDocumentViewer is loaded on the web page thread.
If you want to print a report without displaying it, use the approach shown in the following example.

Ajax call to webmethod gives ERROR 500

I'm a beginner and I want to use ajax to load some data from database to dropdownlist when another dropdownlist selected index in changed
but I'm getting nothing but 500 error
My jquery ajax code
function ddlGroups() {
var s = $("#Content_ddlGroups").find("option:selected").prop("value");
$.ajax({
method: "GET",
contentType: "application/json; charset=utf-8",
//url is the path of our web method (Page name/function name)
url: "../panels/admin/AddProject.aspx/getSubgroups",
data: { Id: s },
dataType: "json",
//called on jquery ajax call success
success: function (result) {
$('#Content_SubGroups').empty();
$.each(result.d, function (key, value) {
$("#Content_ddlGroups").append($("<option></option>").val(value.GroupID).html(value.Title));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ' : ' + result.statusText);
}
});
};
and my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt());
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}
What is the problem??
The jQuery is not the problem here. The 500 error is thrown by the server, so you should review the log of your c# code to find out the details about it and be able to narrow the causes.
In your AJAX Call actually 500 error caused beacuse you have passed
Id:s instead of Id having some digits. Ex. Id : 5.
I see your code if you passed string as a id so in your server side method
you are trying to convert that string to int.That actually causes the 500 error.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt()); // Here You have convert string to Int that's why you got 500 Error.
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}

How to pass value from client side to server side in asp.net?

how to pass the value in below script to the server side
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
FB.api('/me', function(me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('Email').innerHTML = me.email;
document.getElementById('gender').innerHTML = me.gender;
document.getElementById('birth').innerHTML = me.birthday;
document.getElementById('firstname').innerHTML = me.first_name;
})
Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client.You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.
Libraries like jQuery make this kind of thing pretty simple.
In webform2.aspx
<script type="text/javascript">
function LoadValues(me) {
{
var Email = me.email;
var Name = me.name;
var Id = me.id;
var Dob = me.birthday;
var Gender = me.gender;
alert(Email)
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
var data2Send = '{"fbemail": '+Email+', "fbname":'+Name+', "fbid":'+Id+',"fbname":'+Dob+',"fbname":'+Name+' }';
$.ajax({
type: "POST",
url: 'webform2.aspx/Testmethod',
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {console.log(arg) //call successfull
$("#lbltxt").text(arg);
},
error: function (xhr) {
alert(xhr); //error occurred
}
});
}
</script>
In webform2.aspx.cs
[System.Web.Services.WebMethod]
public static string TestMethod(string fbid, string fbemail, string fbsex, string fbdob)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader datareader;
con = new SqlConnection(".......");
cmd = new SqlCommand("SpFacebookInfo", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FbId", fbid);
cmd.Parameters.AddWithValue("#FbEmail", fbemail);
cmd.Parameters.AddWithValue("#FbSex", fbsex);
cmd.Parameters.AddWithValue("#FbDob", fbdob);
datareader = cmd.ExecuteReader();
datareader.Close();
return fbemail;
}
}
Set the value in a hidden variable as u did and do a document.myform.submit();
to go to Page_Load and read the variables

Categories

Resources