Middleware - performance issues - c#

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;
}

Related

Facebook active token failure C# HttpWebRequest

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.

Sending a HttpWebRequest with PFX Certificate C#

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();

Authorize.NET test account working fine on local host but not on live site

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

Windows store apps: web request delayed with 1 minute

My app needs to perform a lot of diffrerent requests (~ 1-2 per second). I have a type of requests which runs continuously(RequestMade -> ResponseReceived -> RequestMade ->...).
If I enter another screen I should start a new set of requests to run continuously as long as I remain in that screen.
The problem is the that the new set of requests (the initial request) is delayed with ~ 1 minute.
Below is posted the code used to perform the requests.
Please note this line is printed out to console at, let's say 12:00:
Debug.WriteLine("Writing RequestStream ("+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
And the lines:
Debug.WriteLine("Request is posting.....(" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
Debug.WriteLine("Reading ResponseStream (" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");
are printed at 12:01 (after 1 minute....)
private class RequestResponseTask
{
private Uri _uri = null;
private string _uriAddress = null;
private WebRequest _webRequest = null;
private ARequest _request = null;
private JsonTextParser _parser = null;
private RequestState _requestState = null;
public RequestResponseTask(ARequest request)
{
// uri address
_uriAddress = CVSCustomRelease.Instance.ReleaseSettings.SelectedPrivateLabel.GetServer(LoginSettings.Instance.SelectedServer).Address
+ CONTEXTUAL_REQUEST_PATH;
// uri
_uri = new Uri(_uriAddress);
// request
_request = request;
_parser = new JsonTextParser();
_requestState = new RequestState(_request);
}
public void StartRequest()
{
Debug.WriteLine("Starting RUN.......(" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");
Task.Factory.StartNew(() =>
{
Debug.WriteLine("RUN Started. - for "+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime());
_request.ResponseReceived = false;
Debug.WriteLine("Before WebRequest ("+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
_webRequest = WebRequest.Create(_uri);
Debug.WriteLine("after WebRequest (" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");
_webRequest.ContentType = "text/x-gwt-rpc;charset=utf-8";
_webRequest.Method = "Post";
_requestState.Request = _webRequest;
// Start the Asynchronous 'BeginGetRequestStream' method call.
Debug.WriteLine("Writing RequestStream ("+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
IAsyncResult r = (IAsyncResult)_webRequest.BeginGetRequestStream(
new AsyncCallback(PostRequest), _requestState);
_requestState.ResetEvent.WaitOne();
Debug.WriteLine("Reading ResponseStream (" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");
IAsyncResult asyncResp = (IAsyncResult)_webRequest.BeginGetResponse(
new AsyncCallback(ReadResponse), _requestState);
});
}
private void PostRequest(IAsyncResult asynchronousResult)
{
Debug.WriteLine("======================================================");
Debug.WriteLine("Request is posting.....(" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
// End the Asynchronus Request.
Stream streamResponse = _webRequest.EndGetRequestStream(asynchronousResult);
ARequest request = _requestState.OriginalRequest;
request.UpdateTimestampRealtime();
string postData = request.GetPostData();
EventsLog.Instance.WriteEvent("Request: " + postData);
// Create a string that is to be posted to the uri.
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
EventsLog.Instance.CurrentSession.AddTraficAmount(TraficType.Outgoing, byteArray.Length);
// Write the data to the stream.
streamResponse.Write(byteArray, 0, postData.Length);
streamResponse.Flush();
Debug.WriteLine("Request POSTED.");
Debug.WriteLine("======================================================");
_requestState.ResetEvent.Set();
}
private async void ReadResponse(IAsyncResult asyncResult)
{
_requestState = (RequestState)asyncResult.AsyncState;
WebRequest myWebRequest = _requestState.Request;
WebResponse response = (WebResponse)myWebRequest.EndGetResponse(asyncResult);
Stream responseStream = response.GetResponseStream();
StreamReader streamRead = new StreamReader(responseStream);
string responseString = await streamRead.ReadToEndAsync();
byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
EventsLog.Instance.CurrentSession.AddTraficAmount(TraficType.Incomming, byteArray.Length);
// build response object
JsonObject jsonObject = _parser.Parse(responseString);
EventsLog.Instance.WriteEvent("Response: " + jsonObject.ToString() + "\nFor Request: " + _requestState.OriginalRequest.RequestId + " | " +_requestState.OriginalRequest.GetType().FullName);
_requestState.ResetEvent.Reset();
// notify listeners
_requestState.OriginalRequest.ResponseReceived = true;
_requestState.OriginalRequest.NotifyResponseListeners(jsonObject as JsonObjectCollection);
}
}
performing a request:
new RequestResponseTask(_request).StartRequest();
My guess: Your code blocks, which leads to a timeout on another thread (that's where the 1 minute comes from) which then leads to unblocking the first thread.
You have things like BeginGetRequestStream and ResetEvent.WaitOne in your code - which shouldn't be needed in a Windows Store code like yours. Try to use WebClient's async methods or HttpClient instead. Use await instead of WaitOne.

WebDAV Exchange 2003 failing when specifying a date

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.

Categories

Resources