Error in $Ajax ASP.NET web method call [async] - c#

I am working over async web method (asmx file) and I need to call this method throughout an ajax jquery method however I am facing a lot of issues because the method uses also Entity Framework to run some other things.
Here is JavaScript:
function SubmitStripeForm() {
// event.preventDefault();
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
// stripeTokenHandler(result.token);
console.log();
var myToken = result.token.id;
$.ajax({
type: "POST",
url: "http://localhost:54355/Account/API/Stripe.asmx/MyStripePayment",
crossDomain: true,
async: false,
data: '{Tok: "' + myToken + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d) {
console.log("Good");
}
else {
console.log("Bad");
}
},
failure: function (response) {
console.log("HORRIBLE");
}
});
}
});
Here is the web method in asp.net c#:
[WebMethod(EnableSession = true)]
public async void MyStripePayment(string Tok)
{
string MyToken = Tok;
using (var context = new CompanyEntities())
{
var collection = (from p in context.COMPANY where p.Id == Company_Id select p);
foreach (var item in collection)
{
// Validation of the object
BillingManagement.Michael Maik = new BillingManagement.Michael();
Maik.name = "Michael";
Maik.id = "114060502";
Maik.number = "83290910";
#region Send Information To Stripe
CancellationToken Token = new CancellationToken();
string Url = "http://localhost:5000/testing/give-your-data";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(Maik);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Token)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
string resString = await response.Content.ReadAsStringAsync();
JObject jObject = JObject.Parse(resString);
string message = (string)jObject["message"];
}
}
}
#endregion
}
}
and this is the error displayed:
POST http://localhost:54355/Account/API/Stripe.asmx/MyStripePayment 500 (Internal Server Error)

have you tried using Try/Catch to get more information about the error? obviously it is something internal, better used it like that and try again to see what error it is.
try
{
// Code
}
catch (Exception ex)
{
console.writeLine(ex);
}
OR
You put an intervention in the catch to be able to see in local variables the values ​​of the "Ex" or save the error somewhere to read it later.

Related

VOID code behind working. String return using Ajax not working. (Checking PayPal details)

I'm trying to convert a void code behind call to PayPal which checks a users PayPal details, to an Ajax call to work in the background.
I'm struggling to
Turn from Void to a String to return the value for Ajax
When I do use my method of a string, it just times out - even if I set timeout to a ridiculously high number. Then it fails and just comes back as undefined.
Working code behind void code:
public async void checkAccAsync()
{
userManager um = new userManager();
var userID = HttpContext.Current.User.Identity.GetUserId();
um.Get(userID);
var subid = um.ppID.Trim();
var token = getToken();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.paypal.com/v1/billing/subscriptions/" + subid))
{
var id = "";
var nextPayment = "";
var status = "";
var payerEmail = "";
var currency = "";
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var response = await httpClient.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
var obj2 = JsonConvert.DeserializeObject<dynamic>(res);
id = obj2.id;
nextPayment = obj2.billing_info.next_billing_time;
if (nextPayment == null)
{
nextPayment = obj2.billing_info.last_payment.time;
var nextPayment2 = Convert.ToDateTime(nextPayment);
nextPayment2.AddMonths(1);
nextPayment = nextPayment2.ToString();
}
status = obj2.status;
status = status.ToLower();
status = FirstLetterToUpper(status);
payerEmail = obj2.subscriber.email_address;
currency = obj2.shipping_amount.currency_code;
um.updatePaypal_noIPN(id, status, "Regular", nextPayment, payerEmail, currency);
}
}
}
Ajax call with String (ideal method), which isn't working.
[WebMethod]
public async System.Threading.Tasks.Task<string> CheckAccAsync()
{
userManager um = new userManager();
var userID = HttpContext.Current.User.Identity.GetUserId();
um.Get(userID);
var subid = um.ppID.Trim();
var token = getToken();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.paypal.com/v1/billing/subscriptions/" + subid))
{
var id = "";
var nextPayment = "";
var status = "";
var payerEmail = "";
var currency = "";
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var response = await httpClient.SendAsync(request);
string res = await response.Content.ReadAsStringAsync();
var obj2 = JsonConvert.DeserializeObject<dynamic>(res);
id = obj2.id;
nextPayment = obj2.billing_info.next_billing_time;
if (nextPayment == null)
{
nextPayment = obj2.billing_info.last_payment.time;
var nextPayment2 = Convert.ToDateTime(nextPayment);
nextPayment2.AddMonths(1);
nextPayment = nextPayment2.ToString();
}
status = obj2.status;
status = status.ToLower();
status = FirstLetterToUpper(status);
payerEmail = obj2.subscriber.email_address;
currency = obj2.shipping_amount.currency_code;
um.updatePaypal_noIPN(id, status, "Regular", nextPayment, payerEmail, currency);
return status + ", "+payerEmail+", ";
}
}
}
And the jQuery which calls it:
$( document ).ready(function() {
$.ajax({
type: "POST",
url: '/WebServices/checkPayPal.asmx/CheckAccAsync',
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError,
timeout: 150000
});
});
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(data, status) { // error 2
alert(data.error)
};
Why isn't my Ajax string method not working?

How to handle jquery array for an asp.net mail list?

I've been struggling about this over two days finding solution. I have form, with inputs, selects and multiple select (email adressess) form is parsed by ajax call to controller, saved to DB and then is email sended. What i need to do is use the list of email adressess from multiple select as an list for mail function. I can't find a suitable method to access the json array in controller to use it as described.
I have tried a multiple methods of converting given data to an array for the mail method, but with no luck.
Ajax form handling and sending to controller:
$("#save").click(function () {
var notifySelection = $('#notification option:selected').toArray().map(item => item.value);
var Data = {
Place: $('#area').val(),
Part: $('#part').val(),
NokRange: $('#nokRange').val(),
Amount: null,
Warehouse: null,
Failure: $('#failureCode').val(),
ResponsibleQPB: $('#responsibleQPB').val(),
ResponsibleLOG: $('#responsibleLOG').val(),
BlockDate: currDate,
BlockedBy: $('#person').val(),
CusSupp: $('#csName').val(),
Description: $('#description').val(),
EndDate: endDate,
Notifications: JSON.stringify(notifySelection)
}
SaveEvent(Data);
});
function SaveEvent(Data) {
$.ajax({
type: "POST",
url: "../PartBlocking/SaveNewCase",
data: Data,
traditional: true,
success: function (Data) {
if (Data.status) {
window.location.replace("http://somepage/PartBlocking/SuccessfulySaved")
}
},
error: function () {
alert('Uložení se nezdařilo!');
}
});
}
Here is controller:
[HttpPost]
public JsonResult SaveNewCase(PartBlockingModel addNew)
{
var status = false;
var Part = addNew.Part;
var Date = addNew.BlockDate;
var Blockedby = addNew.BlockedBy;
var Place = addNew.Place;
var Description = addNew.Description;
var Notifications = addNew.Notifications;
//This is how i've tried handle the array at last try
//string emails = Notifications;
//string[] email = emails.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
db.PartBlocking.Add(addNew);
int saved = db.SaveChanges();
//notifaction
if (saved > 0)
{
try
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplates/NewCase.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{Part}", Part);
body = body.Replace("{Date}", Date);
body = body.Replace("{BlockedBy}", Blockedby);
body = body.Replace("{Place}", Place);
body = body.Replace("{Description}", Description);
MailMessage mail = new MailMessage();
var sub = "SAPNo | Díl č. - " + Part;
var smtp = new SmtpClient
{
Host = ConfigurationManager.AppSettings["smtp"],
Port = int.Parse(ConfigurationManager.AppSettings["portnumber"]),
EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSsl"]),
DeliveryMethod = SmtpDeliveryMethod.Network
};
mail.From = new MailAddress("postmaster#email.com", "Evidována nová neshoda");
mail.To.Add("xx#email.com");
mail.To.Add("xy#email.com");
//This is how i've tried handle the array at last try
//foreach (var item in Notifications)
//{
// mail.To.Add((item).ToString());
//}
mail.IsBodyHtml = true;
mail.Subject = sub;
mail.Body = body;
smtp.Send(mail);
status = true;
}
catch (Exception ex)
{
ViewBag.Error = ex;
}
}
return new JsonResult { Data = new { status } };
}
}
And model:
public class PartBlockingModel
{
//rest of definition for db
......
......
//definition for notifications
public string Notifications { get; set; }
}
The data are correctly inserted into db and if I use only predifinied emails via mail.To.Add("xy#email.com"), email is sended correctly. What i need is to use Notifications list given by jquery as an email list for MailMessage method.
first of all, make sure you javascript object "Data" is the same structure as C# object "PartBlockingModel"
your ajax request must be as the followinf :
$.ajax({
type: "POST",
url: "../PartBlocking/SaveNewCase",
contentType:"application/json; charset=utf-8"
dataType: 'json',
data: JSON.stringify(Data),
traditional: true,
success: function (Data) {
if (Data.status) {
window.location.replace("http://somepage/PartBlocking/SuccessfulySaved")
}
},
error: function () {
alert('Uložení se nezdařilo!');
}
});
I solved the problem.
In my jquery data binding i've changed
Notifications: JSON.stringify(notifySelection)
to:
Notifications: notifySelection.join(',')
and now in my controller works my solution for listing emails as desired and sendig to email addressess from input.
string[] email = Notifications.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in Notifications)
{
mail.To.Add((item).ToString());
}

Not able to consume my second web method in same web service

In continuation to my previous question Not able to consume my web service through jQuery / AJAX i'm facing the problem again. I have now two [WebMethod] in my web service file. First one is FormSubmit() which works fine now and second one is LoginOnClick This is my code:
[WebMethod]
public void LoginOnClick(agentLoginInfo agentLoginObject)
{
string agentID = "";
string agentPassword = "";
try
{
if (agentLoginObject != null)
{
agentID = agentLoginObject.agentID;
agentPassword = agentLoginObject.agentPassword;
}
else
{
Console.Write("No Data");
}
}
catch (Exception e)
{
Console.Write("Error :" + e.Message);
}
RequestBLObject.AgentID = agentLoginObject.agentID.Trim();
RequestBLObject.AgentPassword = agentLoginObject.agentPassword.Trim();
DataTable UserDetails = new DataTable();
UserDetails = BehaviourBLObject.ValidateUsernamePasswordBL(RequestBLObject);
}
This is the AJAX:
function Login() {
var agentLoginObject = {};
var ID = $("#AgentID").val();
var Password = $("#Password").val();
agentLoginObject.AgentID = ID;
agentLoginObject.AgentPassword = Password;
$.ajax({
method: 'POST',
url: 'http://arohar.com/Service.asmx/LoginOnClick',
data: "{agentLoginObject:" + JSON.stringify(agentLoginObject) + "}",
processData: false,
dataType: 'JSON',
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
}
Keeping in mind what mistakes i did last time, i tried my best but i ran into same problem again. Can anyone point out where i went wrong again this time?
UPDATE: I saw on my networks tab and this is what I get every time
System.InvalidOperationException: LoginOnClick Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)

invoke api from ajax asp.net

I have a web Api that allow me to add a multiple Image with with another parameter
(place_Id , is_Main)
I use this code bellow to upload the image
[Route("api/Image")]
[HttpPost]
public async Task<IHttpActionResult> PostImage()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/Images/Places");
var provider = new CustomMultipartFormDataStreamProvider(root);
try
{
// Read the form data.
var task = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = provider.FileData.Select(d =>
{
var info = new FileInfo(d.LocalFileName);
//return new FileDesc(info.Name);
return new FileDesc(info.Name);
});
return fileInfo;
});
int placeId = int.Parse(provider.FormData["placeId"]);
bool isMain = Convert.ToBoolean(provider.FormData["isMain"]);
var listOfAttchments = task.ToList();
string attachmentsPath = Request.RequestUri.Scheme +
System.Uri.SchemeDelimiter +
Request.RequestUri.Host +
(Request.RequestUri.IsDefaultPort ? "" : ":" + Request.RequestUri.Port) +
"/Images/Places/";
Images i = new Images();
if (listOfAttchments.Count > 0)
{
foreach (var item in listOfAttchments)
{
i.FileLocation = item.name;
i.FromUser = true;
i.TableName = "Places";
i.IsMain = isMain;
i.TableId = placeId;
db.Images.Add(i);
}
}
await db.SaveChangesAsync();
return Ok(new
{
result = true,
listAttachmment = listOfAttchments
}
);
}
catch (System.Exception e)
{
return BadRequest(e.StackTrace + "\nTest" + e.Data + "\nTest" + e.InnerException + "\nTest" + e.Message + "\nTest" + e.Source + "\nTest" + e.TargetSite);
}
}
The previous api is in another domain,
and I have a web forms application , that want to upload image from it, using the previous api
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function (i, file) {
data.append(" placeId: 7, isMain: 1");
data.append('image1' + i, file);
});
$("#btn2").click(function () {
jQuery.ajax({
url: '{url}/api/api/Image',
data: data,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function (data) {
alert(data);
}
});
});
I used the above code to invoke it, but I have a problem,
can you help me
Please ensure that you are not receiving XSS Error message (normally other domains are configured that you will not be able to trigger calls from a different domain addresses).
In the below code, i am not sure why do you have /api/api
url: '{url}/api/api/Image',
Please post us the error message you are receiving

call the Web api get method using data params c#

I am able to call the Web api method in client side and now i want make it in c# code. Here i am writing my jquery code.
$(document).ready(function ()
{
$('#btnSubmit').click(function ()
{
var Params =
{
AsOndate: Todate,
BCRefCode: 100,
AccID: 90000
};
$.ajax({
type: "GET",
url: 'http://localhost:51093/api/account/',
//url: 'http://192.168.0.171:51093/api/account/',
data: Params,
dataType: "json",
traditional: true,
success: ajaxSuccess,
error: ajaxError
});
});
and i am calling the web api method
public IEnumerable GetAccountListForMapping(Params param)
{
AccList _AccList = new AccList();
ListParams lstParam = new ListParams();
//lstParam.Add("#FromDate", Fromdate);
lstParam.Add("#AsOnDate", param.AsOndate);
lstParam.Add("#BCRefCode", param.BCRefCode);
lstParam.Add("#AccID", param.AccID);
_AccList = (AccrList)_AccList.GetAccountMappedList(lstParam);
return _AccList;
}
This is working good in jquery call.. And how to write the same C# code
This is what i tried
Params param1 = new Params();
param1.AsOndate = System.DateTime.Today;
param1.AccID = 90000;
param1.BCRefCode = 100;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:51093/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("/api/account", param1, new JsonMediaTypeFormatter()).Result;
if (response.IsSuccessStatusCode)
{.....
}
Got the answer and it worked for me
protected void btnGetdata_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:xxxx/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string param = "AsOnDate=" + System.DateTime.Today + "&AccID=" + 90000 + "&BCRefCode=" + 100;
HttpResponseMessage response = client.GetAsync("/api/account?" + param, HttpCompletionOption.ResponseContentRead).Result;
if (response.IsSuccessStatusCode)
{
var aa = response.Content.ReadAsAsync<object>().Result;
object obj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YourClassName>>(aa.ToString());
}
}
Thanks to all
Use this method.
string param = "AsOndate=" + System.DateTime.Today + "&AccID=" + 90000 + "&BCRefCode=" + 100;
HttpResponseMessage response = client.GetAsync("/api/account?" + param,HttpCompletionOption.ResponseContentRead).Result;
Thanks.
continuing with the answer given by #felix
It will surely get the error as you have not changed the parameter for the api code :
public IEnumerable GetAccountListForMapping(string param)
{
// Your Code
}
and now extract that data from the 'param' string.
I hope this will work.

Categories