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.
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.
Someone else before me wrote a program that takes a bunch of UPS tracking #'s and queries UPS for the status of these. The problem is, with time this program has grown more complex. These queries are now taking too long. It takes about 350ms per query, and some pages have nearly 40 queries, taking about ~15 seconds to load per page.
The method takes in a tracking # as a string and then makes some sort of xml request to UPS which returns the correct data, just very slowly.
Here is the code:
public static List<string> MakeRequest(string tracking)
{
List<string> res = new List<string>();
string xmlStringRequest = "<?xml version=\"1.0\"?>" +
"<AccessRequest xml:lang=\"en-US\">" +
"<AccessLicenseNumber>apilicense</AccessLicenseNumber>" +
"<UserId>apiusername</UserId>" +
"<Password>apipassword</Password>" +
"</AccessRequest>" +
"<?xml version=\"1.0\"?>" +
"<TrackRequest xml:lang=\"en-US\">" +
"<Request>" +
"<TransactionReference>" +
"<CustomerContext>Your Test Case Summary Description</CustomerContext>" +
"<XpciVersion>1.0</XpciVersion>" +
"</TransactionReference>" +
"<RequestAction>Track</RequestAction>" +
"<RequestOption>1</RequestOption>" +
"</Request>" +
"<TrackingNumber>" + tracking + "</TrackingNumber>" +
"</TrackRequest>";
ASCIIEncoding encodedData = new ASCIIEncoding();
byte[] byteArray = encodedData.GetBytes(xmlStringRequest);
//Create Request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://onlinetools.ups.com/ups.app/xml/Track");
wr.Method = "POST";
wr.KeepAlive = false;
//wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = byteArray.Length;
XmlDocument xmlDoc = new XmlDocument();
try
{
//Send XML
Stream SendStream = wr.GetRequestStream();
SendStream.Write(byteArray, 0, byteArray.Length);
SendStream.Close();
//Get Response
WebResponse response = wr.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
//Console.Write(reader.ReadToEnd());
xmlDoc.LoadXml(reader.ReadToEnd());
XmlNode nl = xmlDoc.GetElementsByTagName("ResponseStatusCode").Item(0);
response.Close();
if (nl.InnerText == "1")
{
XmlNode del = xmlDoc.GetElementsByTagName("ActivityLocation").Item(0);
XmlNodeList act = del.ChildNodes;
foreach (XmlNode n in act)
{
if (n.Name == "Code")
{
res.Add(n.InnerText);
}
else if (n.Name == "Description")
{
res.Add(n.InnerText);
}
else if (n.Name == "SignedForByName")
{
res.Add(n.InnerText);
}
else
{
continue;
}
}
res.Add(xmlDoc.GetElementsByTagName("Date").Item(0).InnerText);
res.Add(xmlDoc.GetElementsByTagName("Time").Item(0).InnerText);
}
else
{
res.Add("Tracking Info Not Available");
}
}
catch (Exception ex)
{
xmlDoc = null;
}
return res;
}
I stepped through the code, and what seems to take the longest is this line:
SendStream.Write(byteArray, 0, byteArray.Length);
Is there an obvious way to increase the speed/efficiency of this query? I'm more familiar with jSON than XML.
I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
And the code for the Http call is as following:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); // this is the line where the exception occurs...
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
Can someone help me out with this? It worked fine a day ago, now its giving me this error?
Okay so if anyone is interested, I was able to fix the error by adding the following line before creating the web request (I was able to fix it by going down to Tls12 like this):
`ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`;
Cheers :-)
Edit try this:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// Try using Tls11 if it doesnt works for you with Tls
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = WebRequestMethods.Http.Post;
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
After a number of hours wasted, it turned out to be the Tls protocol version.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
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();
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