I have created a asmx web-service like below:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetEmployeesJSONByID(int sId)
{
try {
string sResult = string.Empty;
List<Employee> lstEmp = new List<Employee>();
List<Employee> lstEmpNew = new List<Employee>();
lstEmp.Add(new Employee { Id = 101, Name = "Nitin", Salary = 10000 });
lstEmp.Add(new Employee { Id = 102, Name = "Dinesh", Salary = 20000 });
switch (sId) {
case 101:
lstEmpNew.Add(new Employee { Id = 101, Name = "Nitin", Salary = 10000 });
break;
case 102:
lstEmpNew.Add(new Employee { Id = 102, Name = "Dinesh", Salary = 20000 });
break;
default:
break;
}
JavaScriptSerializer js = new JavaScriptSerializer();
sResult = js.Serialize(lstEmpNew);
Context.Response.Write(sResult);
} catch (Exception ex) {
Context.Response.Write(ex.Message.ToString());
}
}
I want to test this web-service via Postman. So I deployed in my local IIS and in the postman like below:
In the URL I given as
http://XXXXXX/SampleWebService/Service.asmx/GetEmployeesJSONByID?sId=101
I am getting the Request Format is invalid. How to pass this sId in the postman to test this webservice?
Add the following to the <system.web> block in Web.config file:
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
Well the error image in the question has the request method as POST in Postman and the Source code has UseHttpGet = true for the WebMethod.
Related
Currenty I am implementing a third party payment system through paypal in my MVC application. I have created the payment details are getting through, but at the start of the method when checking if the user is logged in or not (currently the user is not logged in) the redirection link rel is not being appruval_url but it is giving self. Below is the code that I currently have.
This code is set in a controller being called by a button.
//Controller code
// Paypal Payment
private Payment payment;
// Create a payment using APIContext
private Payment CreatePayment(APIContext apiContext, string redirectUrl)
{
var listItems = new ItemList() { items = new List<Item>() };
listItems.items.Add(new Item()
{
name = "M&Ms",
currency = "EUR",
price = "0.7",
quantity = "5",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// Create detials object
var details = new Details()
{
tax = "0",
shipping = "0",
subtotal = "3.5"
};
// Create amount object
var amount = new Amount()
{
currency = "EUR",
total = "3.5",
details = details
};
var transectionList = new List<Transaction>();
transectionList.Add(new Transaction()
{
description = "Testing transection",
invoice_number = Convert.ToString((new Random().Next(100000))),
amount = amount,
item_list = listItems
});
payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transectionList,
redirect_urls = redirUrls
};
return payment.Create(apiContext);
}
// Create Execute Payment method
private Payment ExecutePayment(APIContext apiContext, string payerid, string paymentId)
{
var paymentExecution = new PaymentExecution()
{
payer_id = payerid
};
payment = new Payment() { id = paymentId };
return payment.Execute(apiContext, paymentExecution);
}
// Create Payment with Paypal
public ActionResult PaymentWithPaypal()
{
APIContext apiContext = PaypalConfiguration.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
// Creating payment
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Orders/Index.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = CreatePayment(apiContext, baseURI + "guid=" + guid);
// Gets links returned from Paypal response to create call function
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = string.Empty;
while (links.MoveNext())
{
Links link = links.Current;
var temp = link.rel.ToLower().Trim();
if (link.rel.ToLower().Trim().Equals("appruval_url"))
{
paypalRedirectUrl = link.href;
}
Session.Add(guid, createdPayment.id);
return Redirect(paypalRedirectUrl);
}
}
else
{
var guid = Request.Params["guid"];
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("Failure");
}
}
}
catch (Exception e)
{
PaypalLogger.Log("Error: " + e.Message);
return View("Failure");
}
return View("Success");
}
// webconfig code
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit
http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- Paypal & Log4net -->
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="connectionTimeout" value="360000" />
<add name="requestRetries" value="1" />
<add name="clientId" value="AdzOKk5M7yVA_dWjifjTs6rSAZX9pCRJ7xJ5wX4e_TikEPieiGBJwuMz8h4Su0UVpPVIB5IMgghc7XvZ" />
<add name="clientSecret" value="EEmh_b6MxGLxNNjbI4E-eW96MluwGd0TxU_Ex8Rehyk4yoeHWfiRaS4ERlAVfFrq_izauhIWZukhJ8At" />
</settings>
</paypal>
I'm trying to access PayPal's API to submit invoices to clients through a C#.NET Winforms app, but I am terribly confused. Another user posted this code as a solution to connect:
public class PayPalClient
{
public async Task RequestPayPalToken()
{
// Discussion about SSL secure channel
// http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
// ClientId of your Paypal app API
string APIClientId = "**_[your_API_Client_Id]_**";
// secret key of you Paypal app API
string APISecret = "**_[your_API_secret]_**";
using (var client = new System.Net.Http.HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var jsonString = await webresponse.Content.ReadAsStringAsync();
// response will deserialized using Jsonconver
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
}
}
catch (System.Exception ex)
{
//TODO: Log connection error
}
}
}
public class PayPalTokenModel
{
public string scope { get; set; }
public string nonce { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
}
I'm afraid this is at least one step ahead of me as I can't figure out where in my project it is appropriate to paste the code. Let's just say you created a brand new C# Winforms app. Without getting into the specifics of creating an invoice, etc. What code would I need to support the PayPal API and where in the project does it go? I know I need to get authorization for the app from PayPal, but I'm having trouble finding a good "Getting Started" guide for C# and PayPal. I've created a REST API app on PayPal, so I do have a client ID and "secret" to pass for Oauth authorization - I just can't find a place to do that.
Thanks in advance. I have some C#.net programming experience, but honestly my programming experience mostly goes back to VB6 so I kind of need the big picture explanation. Thanks for your patience!!
Sorry for posting an answer here but I currently do not have enough reputation to post comment. However if you are still looking for a general idea on how to get this done then I can provide a brief example. Since you are using WinForms and PayPal's API, I am assuming you have setup your App.Config file already?
Example-
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="clientId" value="insert_clientid_key_here" />
<add name="clientSecret" value="Insert_client_secret_key_here" />
</settings>
</paypal>
Once this has been addressed then you can make your way over to your form and input what you are going to use. Example:
using System;
using System.Windows.Forms;
using PayPal.Api;
using System.Collections.Generic;
Now that is completed you can create a button to make the API Call.
Example:
private void button1_Click_1(object sender, EventArgs e)
{
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
// Make an API call
var payment = Payment.Create(apiContext, new Payment
{
intent = "sale",
payer = new Payer
{
payment_method = "paypal"
},
transactions = new List<Transaction>
{
new Transaction
{
description = "Transaction description.",
invoice_number = "001",
amount = new Amount
{
currency = "USD",
total = "100.00",
details = new Details
{
tax = "15",
shipping = "10",
subtotal = "75"
}
},
item_list = new ItemList
{
items = new List<Item>
{
new Item
{
name = "Item Name",
currency = "USD",
price = "15",
quantity = "5",
sku = "sku"
}
}
}
}
},
redirect_urls = new RedirectUrls
{
return_url = "http://x.com/return",
cancel_url = "http://x.com/cancel"
}
});
MessageBox.Show("API Request Sent to Paypal");
}
Once completed, test it out and you should have a sandbox call waiting for you.
I have jQuery Ajax method to call a web method in C# code. The code works fine in local environment but it does not work in server. But some web method and jQuery Ajax calls work fine with normal SQL statement, but with a stored procedure in web method which returns some data it does not work. It shows an error message as
{Message: "There was an error processing the request.",StackTrace:"", ExceptionType: ""}
ExceptionType:""
Message:"There was an error processing the request."
StackTrace:""
Here's my Ajax call...
$.ajax({
url: "AutoRFQ_Vendors_SP.aspx/BindGrid"
, type: "POST"
, data: JSON.stringify(objdrpdata)
, contentType: "application/json;"
, success: function (data) {
$body.removeClass("loading");
var vendorsource = {
datatype: "json"
, localdata: data.d
, datafields: [
{
name: 'CommonMakerNameDisplay'
}
, {
name: 'EqpExtendType'
}
, {
name: 'CommonMakerName'
}
, {
name: 'IsForAutoRFQ'
}
, {
name: 'VendorName'
}
, {
name: 'CurrencyCode'
}
, {
name: 'Proc_Vendors_AllowedCurrencyID'
}
, {
name: 'SortCode'
}
, {
name: 'xSortCode'
}
, {
name: 'IsTitle'
}
, {
name: 'NoOfRFQs'
}
, {
name: 'NoOfOrders'
}
, {
name: 'TotalPOAmtInUSD'
}
}
});
Here's my web method:
[WebMethod(EnableSession = true)]
public static string BindGrid(string vslFilter, string yearFilter, string eqpmtFilter)
{
DataTable dt = null;
string gridvendorlist = "";
try
{
if (HttpContext.Current.Session["P_Hub_AutoRFQVendorDataTable"] == null || (string) HttpContext.Current.Session["P_Hub_AutoRFQVslFilter"] != vslFilter || (string) HttpContext.Current.Session["P_Hub_AutoRFQYearFilter"] != yearFilter || (string) HttpContext.Current.Session["P_Hub_AutoRFQEqpmtFilter"] != eqpmtFilter)
{
string vslFilterType = "", vslFilterValue = "";
if (vslFilter.Length == 3)
vslFilter = "VSL-" + vslFilter;
string[] vslType = vslFilter.Trim().Split('-');
if (vslType[0].ToString().Trim().ToUpper() == "VSL")
{
vslFilterType = "VSL";
vslFilterValue = vslType[1].ToString();
}
else if (vslFilter != "-1")
{
vslFilterType = "Group";
vslFilterValue = vslFilter.ToString();
}
string spName = "W_Enh_CommonMakers_RFQVendors";
string[] paramField = { "#CompanyCode", "#VslFilterType",
"#VslFilterValue", "#NoOfYrToShow",
"#EQ_EquipmentID" };
object[] paramValue = { GenFuncs.COMPANYCODE,
vslFilterType,
vslFilterValue,
yearFilter,
eqpmtFilter };
dt = DBFuncs.dbExecuteSP(spName, paramField, paramValue);
HttpContext.Current.Session["P_Hub_AutoRFQVendorDataTable"] = dt;
HttpContext.Current.Session["P_Hub_AutoRFQVendorSelectedRowIndex"] = null;
HttpContext.Current.Session["P_Hub_AutoRFQ_ScrollIndex"] = null;
HttpContext.Current.Session["P_Hub_AutoRFQVslFilter"] = vslFilter;
HttpContext.Current.Session["P_Hub_AutoRFQYearFilter"] = yearFilter;
HttpContext.Current.Session["P_Hub_AutoRFQEqpmtFilter"] = eqpmtFilter;
gridvendorlist = Func_Ajax.GetJson(dt);
}
else
{
dt = (DataTable)HttpContext.Current.Session["P_Hub_AutoRFQVendorDataTable"];
gridvendorlist = Func_Ajax.GetJson(dt);
}
}
catch (Exception err)
{
GenFuncs.AddToErrLog("-1", "xxx", "Error", err.Message, Path.GetFileName(HttpContext.Current.Request.PhysicalPath), "BindGrid");
}
finally
{
dt = null;
}
return gridvendorlist;
}
Is there any extra thing I need to do in server?
After 5 hrs of explore i finally found some silly mistake which was in my web.config file
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>
works fine....Thank you
How do I get the result into my action from my subscribed client?
I have setup hub in my mvc application with signalr with purpose to validate clients between multiple clients providers.
which I am accessing in my controller as:
IHubContext _hubContext = GlobalHost.ConnectionManager.GetHubContext<AmsHub>();
and my mvc action
public ActionResult Index()
{
var result = _hubContext.Clients.All.FindUsers("johny brown");
// how do I access the result?
return View();
}
My subscribed client ( I have multiple ) with implementation
var hubConnection = new HubConnection(hubUrl);
IHubProxy myHubProxy = hubConnection.CreateHubProxy("AmsHub");
myHubProxy.On("FindUsers", (name) =>
{
var foundRecords = new User()
{
FirstName = "Johny",
LastName = "Brown",
Email = "johny.brown#dummy.com",
};
});
There is no return values in SignalR (from Client to Server). You can define a FindUsersCallback function and call it at your Client. On Server side you handle this "Signal" and give your View() back.
myHubProxy.On("FindUsers", (name) = > {
var foundRecords = new User() {
FirstName = "Johny",
LastName = "Brown",
Email = "johny.brown#dummy.com",
};
hubConnection.asmHub.FindUsersCallback(foundRecords);
});
I have a controller which return many datas. then i got "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
i have add my web.config using this. But the error is still occured.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483645" recursionLimit="100">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
then I add new class LargeJsonResult like on this website http://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/
it said like this in controller
return new LargeJsonResult() { Data = output, MaxJsonLength = int.MaxValue };
but how can I use that with many return data? below is my controller
public ActionResult LoadInitData()
{
try
{
Database db = new Database("CON001");
_employee = Helper.Common.GetEmployeeData(db);
EmployeeDAC dacEmployee = new EmployeeDAC(db);
Employee dataEmployee = dacEmployee.GetDataByComputerLogin(GetUser());
if (_employee.SBU == "FB")
{
BrandBudgetDAC dacBrandBudget = new BrandBudgetDAC(db);
List<BrandBudget> dataBrandBudget = dacBrandBudget.GetDataBrandFB();
PostBudgetDAC dacPostBudget = new PostBudgetDAC(db);
List<PostBudget> dataPostBudget = dacPostBudget.GetDataPostFB();
AreaDAC dacArea = new AreaDAC(db);
List<Area> dataArea = dacArea.GetData();
return Json(new { Employee = dataEmployee, BrandBudget = dataBrandBudget, PostBudget = dataPostBudget, Area = dataArea }, JsonRequestBehavior.AllowGet);
}
else
{
BrandBudgetDAC dacBrandBudget = new BrandBudgetDAC(db);
List<BrandBudget> dataBrandBudget = dacBrandBudget.GetData(_employee.SBU);
PostBudgetDAC dacPostBudget = new PostBudgetDAC(db);
List<PostBudget> dataPostBudget = dacPostBudget.GetData(_employee.SBU);
AreaDAC dacArea = new AreaDAC(db);
List<Area> dataArea = dacArea.GetData();
return Json(new { Employee = dataEmployee, BrandBudget = dataBrandBudget, PostBudget = dataPostBudget, Area = dataArea }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(new { Error = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
To reduce the payload, consider making 4 separate ajax calls, each to a different method that returns one of the 4 properties you need.
public ActionResult LoadInitEmployeeData()
{
Employee dataEmployee = ....
....
return Json(dataEmployee, JsonRequestBehavior.AllowGet)
}
public ActionResult LoadBrandBudgetData()
{
List<BrandBudget> dataBrandBudget = ....
return Json(dataBrandBudget, JsonRequestBehavior.AllowGet)
}
etc.