IPN Listner not working MVC3 - paypal

My IPN listner is not working.when i tried with IPN listner Error is showing as follows "We're sorry, we could not send an IPN."
But i can access the IPN Handler url from browser.
here is my IPN handler Code.
public ActionResult IPN()
{
LogMessage ("entering ipn action ");
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
LogMessage ("IPN Response received: " + response + " <-- That was response. . . ");
if (response == "VALID")
{
LogMessage("Response Was Verified");
}
else
{
LogMessage("RESPONSE WAS NOT VERIFIED");
}
return Json("Sucess",JsonRequestBehavior.AllowGet);
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox
? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}

We had faced same issue before I feel it may be because your MVC Application may be published in shared hosting environment Then you have to follow some step to to make MVC RC application works
Here is the blog which help me to solve the issue.Please check this
http://helpnshareidea.blogspot.in/2013/11/mvc3-applications-in-windows-shared.html

Related

Http Post Flutter to SAP

Im trying to use http post to transfer data from flutter to SAP. I can get data without any problem, but post attempt is failing with code 403 (x-csrf-token invalid)
I had the same problem while working in C# but that was resolved using event handler, that triggers just before save (please see below extract of C# code) but i'm unable to find option in flutter. Please guide..
zZSSALE1SRVEntity.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(_container_SendingRequest_Enhance);
zZSSALE1SRVEntity.SaveChanges();
private void _container_SendingRequest_Enhance(object sender, SendingRequest2EventArgs e)
{
HttpWebResponse response;
string empty = string.Empty;
string str = string.Empty;
CookieContainer cookieContainer = new CookieContainer();
OdataSsaleDEV.ZZSSALE1_SRV_Entities zZSSALE1SRVEntity = new OdataSsaleDEV.ZZSSALE1_SRV_Entities(app_uri)
{
Credentials = credentials
};
string str1 ;
if (empty == string.Empty)
{
HttpWebRequest credentials = (HttpWebRequest)WebRequest.Create(zZSSALE1SRVEntity.BaseUri);
credentials.Method = "GET";
credentials.Headers.Add("X-CSRF-Token", "Fetch");
credentials.Credentials = zZSSALE1SRVEntity.Credentials;
cookieContainer = new CookieContainer();
credentials.CookieContainer = cookieContainer;
try
{
response = (HttpWebResponse)credentials.GetResponse();
}
catch (WebException webException)
{
MessageBox.Show(webException.Message);
return;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
return;
}
empty = response.Headers.Get("X-CSRF-Token");
str = response.Headers.Get("Set-Cookie");
credentials.Abort();
}
if (empty != string.Empty)
{
e.RequestMessage.SetHeader("x-csrf-token", empty);
foreach (Cookie cooky in cookieContainer.GetCookies(zZSSALE1SRVEntity.BaseUri))
{
str1 = string.Concat(str1, ";", cooky.ToString());
}
e.RequestMessage.SetHeader("Cookie", str1.Substring(1));
}
Issue resolved.
Actually server requires session cookies (MYSAPSSO and SAP_SESSIONID) along with x-csrf-token.

Error while reading body of request message through JSON

I need to read content of message from the request body in WCF REST service like -
SERVICE SIDE CODE
string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
But I am getting an error on the service side, no matter what I try:
Expecting element 'base64Binary' from namespace 'http://schemas.microsoft.com/2003/10/Serialization/'.. Encountered 'Element' with name 'Human', namespace 'http://numans.hr-xml.org/2007-04-15'.
and the service contract is defined as:
//[OperationContract(Name = "LoadMessages", IsOneWay = true)]
[WebInvoke(Method = "POST",
UriTemplate = "/LoadMessages",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
[Description("Inbound Message")]
void LoadMessages();
and the implementation is as:
public void LoadMessages()
{
string content = string.Empty;
//var request = OperationContext.Current.RequestContext.RequestMessage.GetBody<FileState>();
string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
}
CLIENT SIDE CODE
Content that I'm sending is:
string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
I tried many options to send data from the client like:
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
and also tried this:
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
Posting request:
HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
I also tried serializing/de-serializing at client/server end, but that also is not working.
Can someone please suggest code samples what I can try that might work? Or point out what am I doing wrong.
A few more examples of what I tried with the JSON data :
var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
var details = JObject.Parse(data);
Pasting my client side function for clarity:
HttpClient httpClient = new HttpClient(new HttpClientHandler());
HttpStatusCode statusCode = HttpStatusCode.OK;
string auditMessage = string.Empty;
using (httpClient)
{
var url = ConfigurationManager.AppSettings["APIURL"];
try
{
string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
//var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
//var details = JObject.Parse(data);
//var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
statusCode = executionResult.StatusCode;
if (statusCode == HttpStatusCode.Accepted)
{
file.Status = "Success";
}
}
catch (Exception ex)
{
}
}
Here is my demo:
This is the interface document of the service:
This is the request:
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8012/ServiceModelSamples/service/user");
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-16";
string Json = "{\"Email\":\"123\",\"Name\":\"sdd\",\"Password\":\"sad\"}";
request.ContentLength = Encoding.UTF8.GetByteCount(Json);
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(Json);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
//myResponseStream.ResponseSoapContext
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
Console.WriteLine(retString);
Console.ReadKey();
}
}
Feel free to let me know if the problem persists.
UPDATE
Define the Test class:
[DataContract]
public class Test {
[DataMember]
public string categoryid { get; set; }
[DataMember]
public string fileId { get; set; }
}
the implementation is as:
public void LoadMessages(Test test)
{
Test dataObject = OperationContext.Current.RequestContext.RequestMessage.GetBody<Test>(new DataContractJsonSerializer(typeof(Test)));
Console.WriteLine(dataObject.categoryid);
}

HttpWebRequest 500 internal error but SOAPUI Works

I got an error "The remote server returned an error: (500) Internal Server Error." with status code "ProtocolError"
HttpWebRequest webRequest = null;
XmlDocument soapEnvelopeXml = new XmlDocument();
string requestEnvelopeString = SerializerHelper.ToRequestEnvelopeString(request);
soapEnvelopeXml.LoadXml(requestEnvelopeString);
webRequest = (HttpWebRequest)WebRequest.Create(<<endpointUrl>>);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.KeepAlive = true;
webRequest.ProtocolVersion = HttpVersion.Version11;
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
try
{
using (WebResponse webResponse = webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string responseEnvelopeString = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
string exMessage = ex.Message;
}
When I send the requestEnvelopeString directly through SOAPUI, it works, could anyone suggest how to troubleshoot this?
Found out that the problem is SOAP-ACTION header missing, SOAPUI will auto add to the request.
Thanks
mintssoul

VSTS Web Api gives 403 unauthoratative response

I have created a native app in Azure using App Registration and added required permissions for VSTS Agent
Now, I am able to login using oauth authentication with "ADAL" and able to get the token but when trying to access the web api request it gives Http 403 Response
Here is the code example below
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
HttpResponseMessage res = client.GetAsync(webapiURL).Result;
}
Please let me know what i am missing
thanks in advance
Seems it's an authentication issue, Just check the value of authHeader.
You can reference below samples for the authentication with header:
Sample 1- auth-samples here ;
Sample 2 - REST API
Post the auth sample as reference here:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
namespace DeviceProfileSample
{
public class Program
{
//============= Config [Edit these with your settings] =====================
internal const string vstsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS account; NOTE: This must use HTTPS
internal const string clientId = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1"; //update this with your Application ID from step 2.6 (do not change this if you have an MSA backed account)
//==========================================================================
internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Static value to target VSTS. Do not change
public static void Main(string[] args)
{
AuthenticationContext ctx = GetAuthenticationContext(null);
AuthenticationResult result = null;
try
{
DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync(VSTSResourceId, clientId).Result;
Console.WriteLine("You need to sign in.");
Console.WriteLine("Message: " + codeResult.Message + "\n");
result = ctx.AcquireTokenByDeviceCodeAsync(codeResult).Result;
var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
ListProjects(bearerAuthHeader);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Something went wrong.");
Console.WriteLine("Message: " + ex.Message + "\n");
}
}
private static AuthenticationContext GetAuthenticationContext(string tenant)
{
AuthenticationContext ctx = null;
if (tenant != null)
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
else
{
ctx = new AuthenticationContext("https://login.windows.net/common");
if (ctx.TokenCache.Count > 0)
{
string homeTenant = ctx.TokenCache.ReadItems().First().TenantId;
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant);
}
}
return ctx;
}
private static void ListProjects(AuthenticationHeaderValue authHeader)
{
// use the httpclient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "VstsRestApiSamples");
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
// connect to the REST endpoint
HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=2.2").Result;
// check to see if we have a succesfull respond
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\tSuccesful REST call");
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
}
}
}
}
}
Aren't you missing what authentication,
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token)));
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials)
HttpResponseMessage response = client.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync();
}
I hope this helps.

Using .NET to get results from an API

I wanted to use the Rapidshare API in my .NET app, but I am confused on how you send the request and bring back the result. Do you use Winsock or another method?
URLs are like this:
http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=checkfiles_v1&files=288725357&filenames=my_upload.txt
Thanks.
Check out the System.Net namespace, specifically System.Net.WebClient.
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
Use the WebClient Class.
http://msdn.microsoft.com/en-us/library/system.net.webclient%28VS.80%29.aspx
You can use this class to programatically interact with webpage. Here's some example code to log into a website. You can adapt this to interact with their web API:
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies;
string url = "http://www.jaxtr.com/user/login.jsp";
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer();
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StringBuilder sb = new StringBuilder();
StreamReader reader = new StreamReader(response.GetResponseStream());
while (!reader.EndOfStream)
{
sb.AppendLine(reader.ReadLine());
}
//Get the hidden value out of the form.
String fp = Regex.Match(sb.ToString(), "\"__fp\"\\svalue=\"(([A-Za-z0-9+/=]){4}){1,19}\"", RegexOptions.None).Value;
fp = fp.Substring(14);
fp = fp.Replace("\"", String.Empty);
cookies = request.CookieContainer;
//response.Close();
String requestString = "http://www.jaxtr.com/user/Login.action?tzOffset=6&navigateURL=&refPage=&jaxtrId=" + HttpUtility.UrlEncode(credentials.Username) + "&password=" + HttpUtility.UrlEncode(credentials.Password) + "&Login=Login&_sourcePage=%2Flogin.jsp&__fp="+HttpUtility.UrlEncode(fp);
request = (HttpWebRequest)WebRequest.Create(requestString);
request.CookieContainer = cookies; //added by myself
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response from login:" + response.StatusCode);
String messageText = (message.TruncateMessage && message.MessageText.Length > JaxtrSmsMessage.MAX_MESSAGE_LENGTH ? message.MessageText.Substring(JaxtrSmsMessage.MAX_MESSAGE_LENGTH) : message.MessageText);
String messageURL = "http://www.jaxtr.com/user/sendsms?CountryName=" + HttpUtility.UrlEncode(message.CountryName) + "&phone=" + HttpUtility.UrlEncode(message.DestinationPhoneNumber) + "&message=" + HttpUtility.UrlEncode(messageText) + "&bySMS=" + HttpUtility.UrlEncode(message.BySMS.ToString().ToLower());
request = (HttpWebRequest)WebRequest.Create(messageURL);
request.CookieContainer = cookies;
response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Response from send SMS command=" + response.StatusCode);
StringBuilder output = new StringBuilder();
using (Stream s = response.GetResponseStream())
{
StreamReader sr = new StreamReader(s);
while (!sr.EndOfStream)
{
output.AppendLine(sr.ReadLine());
}
}
response.Close();
}
else
{
Console.WriteLine("Client was unable to connect!");
}
}
catch (System.Exception e)
{
throw new SMSDeliveryException("Unable to deliver SMS message because "+e.Message, e);
}
This particular code logs into Jaxtr, a SMS messaging service, and sends an SMS message.