I have been trying to send a Web Request, but im facing this error "The remote server returned an error: (500) Internal Server Error." on req.GetResponse();
I don't really know if something is missing or if is something wrong.
Can anyone can help me with this?
string soap = "<?xml version='1.0'?> " +
"soapenv:Envelope xmlns:ns='http://www.buzonfiscal.com/ns/xsd/bf/bfcorp/32' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> " +
"<soapenv:Header/> " +
"<soapenv:Body> " +
"<ns:RequestCancelaCFDi uuid='" + this.txtUUID.Text + "' rfcReceptor='" + this.txtReceptor.Text + "' rfcEmisor='" + this.txtEmisor.Text + "'/> " +
"</soapenv:Body> " +
"</soapenv:Envelope> ";
X509Certificate2 cert = new X509Certificate2(#"C:\test.pfx", "password");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://WebRequest.com/bfcorpcfdi32ws");
req.ContentType = "text/xml";
req.Method = "POST";
req.ClientCertificates.Add(cert);
// MessageBox.Show(soap);
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soap);
stmw.Close();
}
}
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();
response = req.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
i dont know how but this code worked perfectly.
string soap = "<?xml version='1.0'?> " +
"<soapenv:Envelope xmlns:ns='http://www.buzonfiscal.com/ns/xsd/bf/bfcorp/32' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> " +
"<soapenv:Header/> " +
"<soapenv:Body> " +
"<ns:RequestCancelaCFDi uuid='" + this.txtUUID.Text + "' rfcReceptor='" + this.txtReceptor.Text + "' rfcEmisor='" + this.txtEmisor.Text + "'/> " +
"</soapenv:Body> " +
"</soapenv:Envelope> ";
X509Certificate2 cert = new X509Certificate2(#"C:\test.pfx", "password");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://WebRequest.com/bfcorpcfdi32ws");
req.ContentType = "text/xml";
req.Method = "POST";
req.ClientCertificates.Add(cert);
MessageBox.Show(soap);
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soap);
stmw.Close();
}
}
try
{
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();
response = req.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{
if (ex is WebException)
{
WebException we = ex as WebException;
WebResponse webResponse = we.Response;
throw new Exception(ex.Message);
}
}
It looks like you might have an error in the XML you are sending to the server.
Your first line should look like this:
string soap = "<?xml version='1.0'?> " +
"<soapenv:Envelope xmlns:ns='http://www.buzonfiscal.com/ns/xsd/bf/bfcorp/32' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> " +
"<soapenv:Header/> " +
"<soapenv:Body> " +
"<ns:RequestCancelaCFDi uuid='" + this.txtUUID.Text + "' rfcReceptor='" + this.txtReceptor.Text + "' rfcEmisor='" + this.txtEmisor.Text + "'/> " +
"</soapenv:Body> " +
"</soapenv:Envelope> ";
You should also be careful and escape the values you are setting. While a little bit more verbose, using XDocument, XElement and XAttribute may help you guarantee you have a valid document.
XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns = "http://www.buzonfiscal.com/ns/xsd/bf/bfcorp/32";
var doc = new XDocument(
new XElement(soapenv + "Envelope",
new XAttribute(XNamespace.Xmlns + "soapenv", soapenv),
new XAttribute(XNamespace.Xmlns + "ns", ns),
new XElement(soapenv + "Header"),
new XElement(ns + "RequestCancelaCFDi",
new XAttribute("uuid", this.txtUUID.Text),
new XAttribute("rfcReceptor", this.txtReceptor.Text),
new XAttribute("rfcEmisor", this.txtEmisor.Text)
)
)
);
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
doc.Save(writer);
}
string soap = builder.ToString();
Related
I obtain an access_token OK from Facebook, but whenever I try to use it, it fails (bad request).
It looks like the access_token is not being sent to the server correctly. I have used Server.UrlEncode to encode it.
Any ideas what I am doing wrong?
string ourAccessToken = "unknown";
//--------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
getAccessToken();
getMe();
}
// -----------------------
private void getAccessToken()
{
string result = "unknown";
try
{
// get app access token
string thisURL = "https://graph.facebook.com/oauth/access_token";
thisURL += "?client_id=" + ourClientID;
thisURL += "&client_secret=" + ourClientSecret;
thisURL += "&grant_type=client_credentials";
thisURL += "&redirect_uri=" + Server.UrlEncode(ourSiteRedirectURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( thisURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode rc = response.StatusCode;
if( rc == HttpStatusCode.OK)
{
StreamReader Sreader = new StreamReader( response.GetResponseStream());
result = Sreader.ReadToEnd();
Sreader.Close();
}
response.Close();
}
catch (Exception exc)
{
result = "ERROR : " + exc.ToString();
}
Response.Write( "<br>result=[" + result + "]");
// extract accessToken
string accessToken = "";
int equalsAt = result.IndexOf( "=");
if( equalsAt >= 0 && result.Length > equalsAt) accessToken = (result.Substring( equalsAt + 1)).Trim();
Response.Write( "<br>accessToken=[" + accessToken + "]");
ourAccessToken = accessToken;
}
// -----------------------
private void getMe()
{
string result = "unknown";
try
{
string thisURL = "https://graph.facebook.com/me?access_token=" + Server.UrlEncode(ourAccessToken);
Response.Write("<br>thisURL=" + thisURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( thisURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode rc = response.StatusCode;
if( rc == HttpStatusCode.OK)
{
StreamReader Sreader = new StreamReader( response.GetResponseStream());
result = Sreader.ReadToEnd();
Sreader.Close();
}
response.Close();
}
catch (Exception ex)
{
Response.Write("<br>getMe Exc: " + ex.Message.ToString() + "<br>");
}
Response.Write("<br>getMe result = " + result + "<br><br>");
}
Thanks
Right settings in App-Dashboard? If you active "Native/Desktop" you can not send API-Calls with this method, see:
https://developers.facebook.com/docs/facebook-login/access-tokens?locale=en_US#apptokens
After a lot of trial and error, I conclude that an App Access Token is not relevant, and that the ClientID and ClientSecret should be used directly. I want my App to generate a set of photographs of registered users. Because the server is making the call, there is no meaning to "me". A set of data can be obtained by preparing a batch process:
string p1 = "access_token=" + Server.UrlEncode(ourClientID + "|" + ourClientSecret);
string p2 = "&batch=" +
Server.UrlEncode( " [ { \"method\": \"get\", \"relative_url\": \"" + chrisFBID + "?fields=name,picture.type(square)\" }, " +
" { \"method\": \"get\", \"relative_url\": \"" + johnFBID + "?fields=name,picture.type(large)\" }, " +
" { \"method\": \"get\", \"relative_url\": \"" + stephFBID + "?fields=name,picture.type(large)\" } ]");
string responseData = "";
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytedata = Encoding.UTF8.GetBytes(p1 + p2);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
responseData = reader.ReadToEnd();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString() + "<br>");
}
Response.Write("<br>" + responseData + "<br><br>");
I also conclude that the FB documentation suffers from the usual fatal flaw of documentation: it has been written by an expert and never tested on a novice user before release.
I'm developing a Middleware for my client and it's found that there are some delay when executing the process.
We are currently investigating what's the exact causes of the issue, from architecture design to coding.
Below are part of the scripts we are calling, and just wondering if the codes itself is optimized and properly written?
There's no error from the codes below, just wondering if there's any performance or coding issues. Tks
public string getResponse(System.Type type, Object input, string taskName, string method)
{
string response = string.Empty;
try
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, input);
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
using (WebClient webClient = new WebClient())
{
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
logger.Info("Sending [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "]");
response = webClient.UploadString(string.Format(Configuration.getTargetURI(), taskName), method, data);
logger.Info("Response of API[" + string.Format(Configuration.getTargetURI(), taskName) + "] successfully retrieved");
logger.Debug("Response: " + response);
}
}
catch (Exception ex)
{
logger.Info("Failed to invoke [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "], Error: " + ex.Message);
logger.Error(ex.Message + ex.StackTrace);
throw ex;
}
return response;
}
public string getResponseNoInput(string taskName, string method)
{
string response = string.Empty;
try
{
WebRequest req = WebRequest.Create(String.Format(Configuration.getTargetURI(), taskName));
req.Method = method;
req.ContentType = "application/json; charset=utf-8";
logger.Info("Sending [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "]");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
response = sr.ReadToEnd();
}
logger.Info("Response of API[" + string.Format(Configuration.getTargetURI(), taskName) + "] successfully retrieved");
logger.Debug("Response: " + response);
}
catch(Exception ex)
{
logger.Info("Failed to invoke [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "], Error: " + ex.Message);
logger.Error(ex.Message + ex.StackTrace);
throw ex;
}
return response;
}
i m testing authorize.net payments and it is working fine on local host payment processing is all good. but when i upload it to my live site with test accounts i get error with
**Object reference not set to an instance of an object. at Billing.readHtmlPage(String url)**
string[] authorizeServer = readHtmlPage("https://test.authorize.net/gateway/transact.dll").Split('|');
//Error is Here
if (authorizeServer[0].ToLower() == "approved" || authorizeServer[0].ToLower() == "1")
{
//Process Payment
}
private String readHtmlPage(string url)
{
String result = "";
//Test Account ID
String strPost =
"x_login=xxxxx"&x_type=AUTH_CAPTURE&x_method=CC&x_tran_key=xxxxx&x_relay_response=&FALSE&" + "x_card_num=" + ccNum.Text + "&x_exp_date=" + ddl_CCM.SelectedValue + "/" +
ddl_CCY.SelectedValue +
"&x_amount=" + lbl_Gtotal.Text +
"&x_first_name=" + ccFName.Text + "&x_last_name=" + ccLName.Text +
"&x_address=" + Server.UrlEncode(hf_street.Value) + "&x_city=" +
hf_city.Value +
"&x_state=" + hf_state.Value + "&x_zip=" + hf_zip.Value;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
Any Help would be nice and much helpful thanks
I am developing push notifications in BB 10 cascades.I am developing my own push initiator and not using Push Service SDK. My Server side push initiator code is as follows.
private static void pushMessageSample(string pushPin, string pushedMessage)
{
string s = "";
try{
String appid = "xxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String password = "xxxxxxxx";
String deliverbefore = DateTime.UtcNow.AddMinutes(5).ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "Z";
String Boundary = "mPsbVQo0a68eIL3OAxnm";
StringBuilder dataToSend = new StringBuilder();
dataToSend.AppendLine("--" + Boundary);
dataToSend.AppendLine("Content-Type: application/xml; charset=UTF-8");
dataToSend.AppendLine("");
dataToSend.AppendLine("<?xml version=\"1.0\"?>");
dataToSend.AppendLine("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\">");
dataToSend.AppendLine("<pap>");
string myPushId = DateTime.Now.ToFileTime().ToString();
dataToSend.AppendLine("<push-message push-id=" + (char)34 + myPushId + (char)34 + " deliver-before-timestamp=" +
(char)34 + deliverbefore + (char)34 + " source-reference=" + (char)34 + appid + (char)34 + ">");
//dataToSend.AppendLine("<push-message push-id=\"" + myPushId + "\" source-reference=\"" + appid + "\">");
dataToSend.AppendLine("<address address-value=\"" + pushPin + "\"/>");
dataToSend.AppendLine("<quality-of-service delivery-method=\"unconfirmed\"/>");
dataToSend.AppendLine("</push-message>");
dataToSend.AppendLine("</pap>");
dataToSend.AppendLine("--" + Boundary);
dataToSend.AppendLine("Content-Type: text/plain");
dataToSend.AppendLine("Push-Message-ID: " + myPushId);
dataToSend.AppendLine("");
dataToSend.AppendLine(pushedMessage);
dataToSend.AppendLine("--" + Boundary + "--");
dataToSend.AppendLine("");
byte[] bytes = Encoding.ASCII.GetBytes(dataToSend.ToString());
String httpURL = "https://cpxxxx.pushapi.eval.blackberry.com/mss/PD_pushRequest";
WebRequest tRequest;
tRequest = WebRequest.Create(httpURL);
//SetProxy(tRequest);
tRequest.Method = "POST";
//tRequest.ContentType = "text/plain";
//tRequest.ContentLength = bytes.Length;
tRequest.Credentials = new NetworkCredential(appid, password);
tRequest.PreAuthenticate = true;
tRequest.ContentType = "multipart/related; boundary=" + Boundary + "; type=application/xml";
tRequest.ContentLength = bytes.Length;
string rawCredentials = string.Format("{0}:{1}", appid, password);
tRequest.Headers.Add("Authorization",
string.Format(
"Basic {0}",
Convert.ToBase64String(Encoding.UTF8.GetBytes(rawCredentials))));
SetBasicAuthHeader(tRequest, appid, password);
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex1)
{
s = ex1.Message.ToString();
}
}
But I am getting The remote server returned an error: (401) Unauthorized error. How to resolve it?
For production: use https://cpxxxx.pushapi.na.blackberry.com/mss/PD_pushRequest. For testing you can use pushapi.eval.blackberry.com
I am using the following code to retrieve emails from an Exchange 2003 server. All was working on Friday and now it fails.
From some investigation I have narrowed it to the targetDate variable. Seems if the date is in April it fails with a 400 back from the server. I have commented this line out and tried various dates 2012-3-29, 2012-4-1, 2012-4-10 (today) and the ones in April seem to fail.
Some kind of sick April fools joke?
The code itself is derived from this article: http://www.codeproject.com/Articles/42458/Using-Exchange-2003-with-Webdav-Send-Retrieve-Atta
public XmlDocument GetMailAll()
{
HttpWebRequest request = default(HttpWebRequest);
HttpWebResponse response = default(HttpWebResponse);
string rootUri = null;
string query = null;
byte[] bytes = null;
Stream requestStream = default(Stream);
Stream responseStream = default(Stream);
XmlDocument xmlDoc = default(XmlDocument);
xmlDoc = new XmlDocument();
try
{
DateTime targetDateTime = DateTime.Today.AddDays(-5);
String targetDate = ""+targetDateTime.Year + "-" + targetDateTime.Month + "-" + targetDateTime.Day;
rootUri = server + "/Exchange/" + alias + "/" + inbox;
query = "<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" xmlns:m=\"urn:schemas:httpmail:\">"
+ "<D:sql>SELECT \"urn:schemas:httpmail:hasattachment\", \"DAV:displayname\", "
+ "\"urn:schemas:httpmail:from\", \"urn:schemas:httpmail:subject\", "
//+ "\"urn:schemas:httpmail:htmldescription\"," //Return full body (not necessary right now)
+ "\"urn:schemas:httpmail:datereceived\", \"urn:schemas:httpmail:read\" FROM \"" + rootUri
+ "\" WHERE \"DAV:ishidden\" = false "
+ "AND \"DAV:isfolder\" = false "
//+ "AND \"urn:schemas:httpmail:read\" = false"
+ "AND \"urn:schemas:httpmail:datereceived\" >= CAST(\"" + targetDate + "T00:00:000Z\" AS 'dateTime.tz')"
+ "</D:sql></D:searchrequest>";
request = (HttpWebRequest)WebRequest.Create(rootUri);
request.Timeout = 5000;
request.Credentials = new NetworkCredential(alias, password, domain);
request.Method = "SEARCH";
request.ContentType = "text/xml";
request.Headers.Add("Translate", "F");
bytes = System.Text.Encoding.UTF8.GetBytes(query);
request.ContentLength = bytes.Length;
requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
response = (HttpWebResponse)request.GetResponse();
authCookies = new List<Cookie>();
foreach(Cookie cookie in response.Cookies)
{
authCookies.Add(cookie);
}
responseStream = response.GetResponseStream();
xmlDoc.Load(responseStream);
responseStream.Close();
}
catch (WebException ex)
{
if (ex.Response == null)
{
throw new Exception();
}
else if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
{
throw new ExchangeCatastrophicException();
}
else
{
throw new ExchangeFailedException();
}
}
catch (Exception ex)
{
throw;
}
return xmlDoc;
}
Finally got it working. The exact targetDate to cast including the T00:00:..Z part must match the specification on http://msdn.microsoft.com/en-us/library/aa123600%28v=exchg.65%29.aspx
I now have:
DateTime targetDateTime = DateTime.Today;
string targetDate = targetDateTime.ToString("yyyy-MM-dd");
snip
+ "AND \"urn:schemas:httpmail:datereceived\" >= CAST(\"" + targetDate + "T00:00:00Z" + "\" AS 'dateTime.tz')"
Note that the seconds part is two zero's instead of three.