I have the following code using the TcpClient
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("username" + ":" + "password");
string follow = "track=soccer,twitter";
byte[] encode_follow = System.Text.Encoding.UTF8.GetBytes(follow);
using (TcpClient client = new TcpClient())
{
string requestString = "POST /1/statuses/filter.json HTTP/1.1\r\n";
requestString += "Host: stream.twitter.com\r\n";
requestString += "User-Agent: www.site.com\r\n";
requestString += "Referer: http://www.site.com\r\n";
requestString += "Content-Type: application/x-www-form-urlencoded\r\n";
requestString += "Authorization: " + "Basic " + Convert.ToBase64String(encbuff) + "\r\n";
requestString += "Content-length: " + follow.Length + "\r\n";
requestString += "Connection: keep-alive\r\n";
requestString += "\r\n";
requestString += follow;
requestString += "\r\n\r\n";
client.Connect("stream.twitter.com", 80);
//client.ReceiveTimeout = 100;
using (NetworkStream stream = client.GetStream())
{
// Send the request.
StreamWriter writer = new StreamWriter(stream);
writer.Write(requestString);
writer.Flush();
// Process the response.
StreamReader rdr = new StreamReader(stream);
while (!rdr.EndOfStream)
{
Console.WriteLine(rdr.ReadLine());
Console.WriteLine("IS end: " + rdr.EndOfStream.ToString());
}
}
}
What happens though is that the Console.WriteLine(rdr.ReadLine()); line will print out statuses for a few seconds than it would stop + not hit the break point there anymore, even though it's still connected.
What it should be doing is continuing to write the statuses in the console, since it's a keep-alive connection and the 'Twitter' keyword gets mentioned a few times every few seconds continuously.
Any ideas what could be causing this issue?
Check this out:
public class Program
{
public static void Main()
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("username", "password");
client.OpenReadCompleted += (sender, e) =>
{
using (var reader = new StreamReader(e.Result))
{
while (!reader.EndOfStream)
{
// TODO: feed this to your favorite JSON parser
Console.WriteLine(reader.ReadLine());
}
}
};
client.OpenReadAsync(new Uri("http://stream.twitter.com/1/statuses/filter.json?track=soccer,twitter"));
}
Console.ReadLine();
}
}
Should make things easier.
Related
I am fairly new to programming. I require exception handling for my HttpWebRequest to an Api. Below is my code, I haven't done error handling before so just an example of how to accomplish this will be appreciated.
private void button1_Click(object sender, EventArgs e)
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
1) Create a folder named as "ExceptionTextFile" inside your application
2) Create a Separate Class like below to log the exception
using System;
using System.IO;
using context = System.Web.HttpContext;
//Define your application namespace here
namespace YourApplicationNamespace
{
public static class ExceptionLogging
{
private static String ErrorlineNo, Errormsg, extype, exurl, ErrorLocation;
public static void SendErrorToText(Exception ex)
{
var line = Environment.NewLine + Environment.NewLine;
ErrorlineNo = ex.StackTrace.ToString();
Errormsg = ex.Message;
extype = ex.GetType().ToString();
exurl = context.Current.Request.Url.ToString();
ErrorLocation = ex.Message.ToString();
try
{
//Create a folder named as "ExceptionTextFile" inside your application
//Text File Path
string filepath = context.Current.Server.MapPath("~/ExceptionTextFile/");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
//Text File Name
filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt";
if (!File.Exists(filepath))
{
File.Create(filepath).Dispose();
}
using (StreamWriter sw = File.AppendText(filepath))
{
string error = "Log Written Date:" + " " + DateTime.Now.ToString()
+ line + "Error Line No :" + " " + ErrorlineNo + line
+ "Error Message:" + " " + Errormsg + line + "Exception Type:" + " "
+ extype + line + "Error Location :" + " " + ErrorLocation + line
+ " Error Page Url:" + " " + exurl + line + line;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(line);
sw.WriteLine(error);
sw.WriteLine("--------------------------------*End*------------------------------------------");
sw.WriteLine(line);
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
e.ToString();
}
}
}
}
After that inside your button click event define try...catch block and log the exception like below
private void button1_Click(object sender, EventArgs e)
{
try
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
catch (Exception e)
{
ExceptionLogging.SendErrorToText(e);
}
}
If any error appears go to the "ExceptionTextFile" folder and check the log. The exception would be logged there.
Try and revert me back if this solves your problem or not
I am trying to post a request in a C# Console Application and I am getting this error. The request is working in SOAPUI, there is no WSDL File so I have to load the XML directly in the code (I highly suspect this is where the error is coming from).
The output on the Console Application is below:
The SOAPUI Request that is working is as Follows:
Here is the C# Console Application that I am using to send this SOAP Request.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace IMSPostpaidtoPrepaid
{
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
obj.createSOAPWebRequest();
}
//Create the method that returns the HttpWebRequest
public void createSOAPWebRequest()
{
//Making the Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(#"http://127.1.1.0:9090/spg");
//Content Type
Req.ContentType = "text/xml;charset=utf-8";
Req.Accept = "text/xml";
//HTTP Method
Req.Method = "POST";
//SOAP Action
Req.Headers.Add("SOAPAction", "\"SOAPAction:urn#LstSbr\"");
NetworkCredential creds = new NetworkCredential("username", "pass");
Req.Credentials = creds;
Req.Headers.Add("MessageID", "1"); //Adding the MessageID in the header
string DN = "+26342720450";
string DOMAIN = "ims.telone.co.zw";
//Build the XML
string xmlRequest = String.Concat(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>",
"<soap:Envelope",
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
" xmlns:m=\"http://www.huawei.com/SPG\"",
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"",
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">",
" <soap:Body>",
"<m:LstSbr xmlns=\"urn#LstSbr\">",
" < m:DN >", DN, "</ m:DN>",
" < m:DOMAIN >", DOMAIN, "</ m:DOMAIN>",
" </m:LstSbr>",
" </soap:Body>",
"</soap:Envelope>");
//Pull Request into UTF-8 Byte Array
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
//Set the content length
Req.ContentLength = reqBytes.Length;
//Write the XML to Request Stream
try
{
using (Stream reqStream = Req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception of type " + ex.GetType().Name + " " + ex.Message );
Console.ReadLine();
throw;
}
//Headers and Content are set, lets call the service
HttpWebResponse resp = (HttpWebResponse)Req.GetResponse();
string xmlResponse = null;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine(xmlResponse);
Console.ReadLine();
}
}
}
Here is my basic method that I use to post to a web service.
static XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
static XNamespace topNs = "Company.WebService";
private System.Net.HttpWebResponse ExecutePost(string webserviceUrl, string soapAction, string postData) {
var webReq = (HttpWebRequest)WebRequest.Create(webserviceUrl);
webReq.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
webReq.ContentType = "text/xml;charset=UTF-8";
webReq.UserAgent = "Opera/12.02 (Android 4.1; Linux; Opera Mobi/ADR-1111101157; U; en-US) Presto/2.9.201 Version/12.02";
webReq.Referer = "http://www.company.com";
webReq.Headers.Add("SOAPAction", soapAction);
webReq.Method = "POST";
var encoded = Encoding.UTF8.GetBytes(postData);
webReq.ContentLength = encoded.Length;
var dataStream = webReq.GetRequestStream();
dataStream.Write(encoded, 0, encoded.Length);
dataStream.Close();
System.Net.WebResponse response;
try { response = webReq.GetResponse(); }
catch {
("Unable to post:\n" + postData).Dump();
throw;
}
return response as System.Net.HttpWebResponse;
}
I then can build whatever I want around this to do what I need. For example here is how I would use it.
private void CreateTransaction(string webServiceUrl, string ticket, double costPerUnit) {
string soapAction = "Company.WebService/ICompanyWebService/CreatePurchaseTransaction";
var soapEnvelope = new XElement(soapNs + "Envelope",
new XAttribute(XNamespace.Xmlns + "soapenv", "http://schemas.xmlsoap.org/soap/envelope/"),
new XAttribute(XNamespace.Xmlns + "top", "Company.WebService"),
new XElement(soapNs + "Body",
new XElement(topNs + "CreatePurchaseTransaction",
new XElement(topNs + "command",
new XElement(topNs + "BillTransaction", "true"),
new XElement(topNs + "BillingComments", "Created By C# Code"),
new XElement(topNs + "Department", "Development"),
new XElement(topNs + "LineItems", GetManualPurchaseLineItems(topNs, costPerUnit)),
new XElement(topNs + "Surcharge", "42.21"),
new XElement(topNs + "Tax", "true"),
new XElement(topNs + "TransactionDate", DateTime.Now.ToString("yyyy-MM-dd"))
))));
var webResp = ExecutePost(webServiceUrl, soapAction, soapEnvelope.ToString());
if (webResp.StatusCode != HttpStatusCode.OK)
throw new Exception("Unable To Create The Transaction");
var sr = new StreamReader(webResp.GetResponseStream());
var xDoc = XDocument.Parse(sr.ReadToEnd());
var result = xDoc.Descendants(topNs + "ResultType").Single();
if (result.Value.Equals("Success", StringComparison.CurrentCultureIgnoreCase) == false)
throw new Exception("Unable to post the purchase transaction. Look in the xDoc for more details.");
}
private IEnumerable<XElement> GetManualPurchaseLineItems(XNamespace topNs, double costPerUnit) {
var lineItems = new List<XElement>();
lineItems.Add(new XElement(topNs + "PurchaseLineItem",
new XElement(topNs + "Count", "5"),
new XElement(topNs + "ExpenseClass", "Tech Time"),
new XElement(topNs + "ItemName", "Brushing and Flossing"),
new XElement(topNs + "Location", "Your House"),
new XElement(topNs + "UnitCost", costPerUnit.ToString("#.00"))));
return lineItems;
}
You would need to adapt this into your console application, but does this help get you going?
Out of no where, my twitter API calls, specificly my first step in the 3-legged auth, stopped working. I've compared the timestamps, keys and everything with the OAuth signature generator tool, and they all match (execpt oauth_nonce but thats the point I guess). Here is my code. Any suggestions or small observations would be appreciated.
protected void RequestToken()
{
string oauthcallback = Request.Url.Host + "/TwitterCallback.aspx";
string oauthconsumerkey = "xxx-consumerkey";
string oauthconsumersecret = "xxx-consumerSecret";
string oauthtokensecret = string.Empty;
string oauthtoken = string.Empty;
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string url = "https://api.twitter.com/oauth/request_token?oauth_callback=" + oauthcallback;
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_callback", Uri.EscapeDataString(oauthcallback));
//Build the signature string
string baseString = String.Empty;
baseString += "POST" + "&";
baseString += Uri.EscapeDataString(url.Split('?')[0]) + "&";
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&");
}
//Remove the trailing ambersand char last 3 chars - %26
//baseString = baseString.Substring(0, baseString.Length - 3);
//Build the signing key
string signingKey = Uri.EscapeDataString(oauthconsumersecret) +
"&" + Uri.EscapeDataString(oauthtokensecret);
//Sign the request
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
//Tell Twitter we don't do the 100 continue thing
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#url);
string authorizationHeaderParams = String.Empty;
authorizationHeaderParams += "OAuth ";
authorizationHeaderParams += "oauth_nonce=" + "\"" +
Uri.EscapeDataString(oauthnonce) + "\",";
authorizationHeaderParams += "oauth_signature_method=" + "\"" +
Uri.EscapeDataString(oauthsignaturemethod) + "\",";
authorizationHeaderParams += "oauth_timestamp=" + "\"" +
Uri.EscapeDataString(oauthtimestamp) + "\",";
authorizationHeaderParams += "oauth_consumer_key=" + "\"" +
Uri.EscapeDataString(oauthconsumerkey) + "\",";
authorizationHeaderParams += "oauth_signature=" + "\"" +
Uri.EscapeDataString(oauthsignature) + "\",";
authorizationHeaderParams += "oauth_version=" + "\"" +
Uri.EscapeDataString(oauthversion) + "\"";
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Allow us a reasonable timeout in case Twitter's busy
webRequest.Timeout = 3 * 60 * 1000;
try
{
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
var uri = new Uri("https://test.dk?" + responseFromServer);
var token = HttpUtility.ParseQueryString(uri.Query).Get("oauth_token"); ;
var tokensecret = HttpUtility.ParseQueryString(uri.Query).Get("oauth_token_secret");
Response.Write(responseFromServer);
Response.Redirect("https://api.twitter.com/oauth/authorize?force_login=true&oauth_token=" + token);
}
catch (Exception ex)
{
Response.Write(ex.GetBaseException());
}
}
The error obviously happens when I do the HTTP request webRequest.GetResponse()
It returns a 401 unauthorized
Apperently you have to include the oauth version number in the URL now, or else it will fall back to the oldest version (or maybe the newest, can't remember).
Providing /oath/1.0/ or /1.0/oauth/ or what ever solved my issue as i recall it (it's been a while).
Can anybody explain how to integrate third party payment migs (MasterCard Virtual Payment Client) in C#?
Anyone who has done a similar project or has any clue as to what am missing here, can be of great help to me. In case of any question, I shall clarify in details. Thank you.
try
{
//Define Variables
string MerchantId = "00000047";
string Amount = txtAmountUSD.Text.Trim();
long PhoneNumber=long.Parse( txtPhoneNumber.Text.Trim().ToString());
string AccessCode = "4EC13697";
string SECURE_SECRET = "A1A3999770F5893719AE0076C7F18834";
string ReturnUrl = "http://localhost:2035/Core/frmMoneyTransfer.aspx";
string DestinationUrl = "https://migs.mastercard.com.au/vpcpay?";
string MerchantTransactionRef = Amount + DateTime.Now;
string Command = "Pay";
var HashData = SECURE_SECRET;
string postData = "vpc_Merchant=" + MerchantId;
postData += ("&vpc_Amount=" + Amount);
postData += ("&vpc_AccessCode=" + AccessCode);
postData += ("&vpc_Command=" + Command);
postData += ("&vpc_MerchTxnRef=" + MerchantTransactionRef);
postData += ("&vpc_ReturnURL=" + ReturnUrl);
postData += ("&vpc_SecureHashType=" + "SHA256");
postData += ("&vpc_OrderInfo=" + PhoneNumber );
postData += ("&vpc_Version=" + "1.0");
postData+=("&vpc_SecureHash="+SECURE_SECRET );
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(DestinationUrl);
request1.Method = "POST";
request1.ContentType = "application/x-www-form-urlencoded";
request1.AllowAutoRedirect = true;
request1.ProtocolVersion = HttpVersion.Version11;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postData);
request1.ContentLength = bytes.Length;
Stream requestStream = request1.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request1.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
Response.Redirect(request1.Address.ToString(), false );
stream.Dispose();
reader.Dispose();
}
catch (Exception Ex)
{
lblInfo.Text= Ex.Message.ToString();
}
The following function will pull down first X messages from Twitter firehose, but looks like WebResponse blocks and never exits the function:
public void GetStatusesFromStream(string username, string password, int nMessageCount)
{
WebRequest request = WebRequest.Create("http://stream.twitter.com/1/statuses/sample.json");
request.Credentials = new NetworkCredential(username, password);
using (WebResponse response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
if (nMessageCount-- < 0)
break;
}
Console.WriteLine("Start iDispose");
}
Console.WriteLine("Never gets here!!!");
}
}
Console.WriteLine("Done - press a key to exit");
Console.ReadLine();
}
But the following works fine:
public void GetStatusesFromStreamOK(string username, string password, int nMessageCount)
{
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
//request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(encbuff));
string requestString = "GET /1/statuses/sample.json HTTP/1.1\r\n";
requestString += "Authorization: " + "Basic " + Convert.ToBase64String(encbuff) + "\r\n";
requestString += "Host: stream.twitter.com\r\n";
requestString += "Connection: keep-alive\r\n";
requestString += "\r\n";
using (TcpClient client = new TcpClient())
{
client.Connect("stream.twitter.com", 80);
using (NetworkStream stream = client.GetStream())
{
// Send the request.
StreamWriter writer = new StreamWriter(stream);
writer.Write(requestString);
writer.Flush();
// Process the response.
StreamReader rdr = new StreamReader(stream);
while (!rdr.EndOfStream)
{
Console.WriteLine(rdr.ReadLine());
if (nMessageCount-- < 0)
break;
}
}
}
Console.WriteLine("Done - press a key to exit");
Console.ReadLine();
}
What am I doing wrong?
Cast your WebRequest as an HttpWebRequest, then before the break call request.Abort()
Looks like it has something to do with the disposal process or "using"...
The following code works fine (no "using" statements):
public static void GetStatusesFromStream(string username, string password, int nMessageCount)
{
WebRequest request = WebRequest.Create("http://stream.twitter.com/1/statuses/sample.json");
request.Credentials = new NetworkCredential(username, password);
WebResponse response = request.GetResponse();
{
var stream = response.GetResponseStream();
{
var reader = new StreamReader(stream);
{
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
if (nMessageCount-- < 0)
break;
}
}
Console.WriteLine("Never gets here!!!");
}
}
Console.WriteLine("Done - press a key to exit");
Console.ReadLine();
}