Authorization issues with Ajax - javascript

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?

Related

IIS connections overload and CPU running high

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.

Why is my C# method not being called from AJAX?

I am trying to call the following C# method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getJSONdata()
{
string jsonString = "";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Dot> _Dot = new List<Dot>();
while (reader.Read())
{
Dot dot = new Dot();
dot.x = (int.Parse(reader["xCoord"].ToString()));
dot.y = (int.Parse(reader["yCoord"].ToString()));
if (reader["DrawID"] != DBNull.Value)
dot.i = (int.Parse(reader["DrawID"].ToString()));
_Dot.Add(dot);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
jsonString = jss.Serialize(_Dot);
}
}
}
System.Diagnostics.Debug.WriteLine(" JSON: " + jsonString);
return jsonString;
}
Here is my JavaScript code:
$.ajax({
url: 'Default.aspx/getJSONdata',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
First, I am getting the ajax error. No idea why it's not called.
Second, I am still not sure I am returning the correct JSON data I want, whether in the correct format or not. Thanks for your help.
Edit. It is returning a JSON string correctly.
Note: the connectionString works in another function, so that's not it.
Download and install Fidder4.
This will allow you to see the traffic between your page and your server. You can see the actual call URL and then paste it into a browser to see what it returns. This will give you a tool to solve this type of problem going forward.

How to download file from System.Web.HttpContext.Current.Response.BinaryWrite(byteArray); from javascript instead of C#

I have a C# method that works if you call it from another C# method, but not from javascript. How do I make it work from my ajax call?
I need to get a file based on an ID that is passed in, so I have an ajax post with the statusID. That ID is pulling the proper file in my C# method, it is just not giving the file save dialog.
However, if I call this from my C# page load method with a static statusID for testing purposes, it works just fine.
Here is the C# method:
public void Get_Attachment_By_StatusID(int statusID)
{
SqlDataReader _reader = null;
string _connString = "Data Source=133.31.32.33;Initial Catalog=Reports;Integrated Security=True";
string sql = "SELECT a.StatusID ,a.DocumentName ,a.MIMETypeID ,a.Binary ,a.CreatedDate ,a.CreatedBy " +
",b.MIMEType FROM Attachments a Inner join MIME_Types b on a.MIMETypeID = b.ID " +
"WHERE [StatusID] = {0} ";
sql = string.Format(sql, statusID);
try
{
_connection = new SqlConnection(_connString);
_connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, _connection))
{
cmd.CommandType = System.Data.CommandType.Text;
_reader = cmd.ExecuteReader();
if (_reader.HasRows)
{
while (_reader.Read())
{
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType = _reader["MIMEType"].ToString();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + _reader["DocumentName"].ToString() + ";");
byte[] b = (byte[])_reader["Binary"];
System.Web.HttpContext.Current.Response.BinaryWrite(b);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
}
_reader.Close();
_connection.Close();
}
}
catch (Exception ex)
{
//Log exception to error Logging app
string err = ex.ToString();
}
finally
{
if (_connection != null)
_connection.Close();
if (_reader != null)
_reader.Close();
}
}
Here is how I am calling it from my page, in javascript:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID';
$.ajax({
url: url,
type: 'post',
cache: false,
data: JSON.stringify({ "statusID": statusID }),
contentType: 'application/json',
success: function (data) {
}
});
}
Nothing happens. In Chrome, I don't see anything in the javascript console, and in IE, my console spits this out: "XML5619: Incorrect document syntax."
Again, if I go into the controller, and call the method in my page load method, it presents the save file dialog and saves the file just fine. So I must be doing something wrong with my javascript/jquery/ajax...
I am new to MVC4 and know I'm missing something here. What am I missing?
Use window.open('CONTROLLER_URL/STATUS_ID'); instead of an AJAX request.
<a target="_blank" href="javascript:window.open('/Home/Get_Attachment_By_StatusID/12345');">Test</a>
Here's one suggestion, largely based on answer from LastCoder:
Decorate your action with the [HttpGet] attribute and change the parameter name to id:
[HttpGet]
public void Get_Attachment_By_StatusID(int id) ...
Now in your client-side code, simply do this:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID/'+statusID;
window.location=url;
}

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

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources