Why does WebResponse never end when reading twitter firehose stream? - c#

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

Related

How to get Data from InfluxDB API used HttpClient

Please somebody help me...
How to get InfluxDB v2 query Data...? used HttpClient.
I want to get query result data but no result just empty result
that image is I wanna data result.
this is my code, can you give me Resolutions( 1. post(URL, query) -> read data in one method solutions 2. post method, get method 2 method solutions)
public async System.Threading.Tasks.Task<HttpResponseMessage> RequestQuery()
{
// client = new HttpClient();
HttpClient client = new HttpClient();
int refreshTime = 5;
client.DefaultRequestHeaders.Add("Authorization", "Token " + token);
client.DefaultRequestHeaders.Add("Accept", "application/csv");
var fluxQuery = "from(bucket: \"DT_Object\")\n"
+ "|> range(start: -7d)"
+ "|> filter(fn: (r) => r[\"_measurement\"] ==\" NPC\")"
+ "|> filter(fn: (r) => r[\"NAME\"] == \"NPC\")"
+ "|> filter(fn: (r) => r[\"_field\"] == \"X\" or r[\"_field\"] == \"Y\" or r[\"_field\"] == \"Z\")"
+ "|> aggregateWindow(every: "+ refreshTime + "s, fn: mean, createEmpty: false)"
+ "|> yield(name: \"mean\")";
var data = new StringContent(fluxQuery, Encoding.UTF8, "application/vnd.flux");
var response = await client.PostAsync(requestUrl, data);
Debug.Log(response);
if (response.ReasonPhrase == "OK")
{
GetData1();
}
string result = response.Content.ReadAsStringAsync().Result;
client.Dispose();
return response;
}
public string GetData1()
{
string responseFromServer = string.Empty;
try
{
WebRequest request = WebRequest.Create("http://localhost:8086/api/v2/query?org=DT_navigator");
request.Method = "GET";
request.ContentType = "text/csv";
request.Timeout = 10 * 1000; // 10초
request.Headers.Add("Authorization", "Token " + token);
using (WebResponse response = request.GetResponse())
using (Stream dataStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(dataStream))
{
responseFromServer = reader.ReadToEnd();
}
Debug.Log("Influx data : " + responseFromServer);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
return responseFromServer;
}

Post XML to a IP Camera using C#

I have a digital IP camera. It is preset to use set static IP address, and I have asked the manufacturer whether they have an API I can call to set it to DHCP.
They replied:
PUT /Network/interfaces/1/ipAddress HTTP/1.1
Authorization: Basic YWRtaW46MTIzNDU=
Content-Type:text/xml
Content-Length:387
<IPAddress version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
<ipVersion>v4</ipVersion>
<addressingType>dynamic</addressingType>
<ipAddress>172.2.62.49</ipAddress>
<subnetMask>255.255.255.0</subnetMask>
<DefaultGateway>
<ipAddress>172.2.62.1</ipAddress>
</DefaultGateway>
<PrimaryDNS>
<ipAddress>0.0.0.0</ipAddress>
</PrimaryDNS>
</IPAddress>
So, I translated that to:
private void button1_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest req = null;
WebResponse rsp = null;
string uri = "http://192.0.0.64/Network/interfaces/1/ipAddress";
req =(HttpWebRequest) WebRequest.Create(uri);
req.UseDefaultCredentials = true;
//req.Credentials = new NetworkCredential("admin", "12345"); //I have tried using this as well as these are the default admin/pw supplied
req.Method = "PUT";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentLength = 387;
string _cred = string.Format("{0} {1}", "Basic", "YWRtaW46MTIzNDU=");
req.Headers[HttpRequestHeader.Authorization] = _cred;
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(GetDHCPPost());
writer.Close();
rsp = req.GetResponse();
}
catch (Exception ex)
{
//errors here >> cannot connect to server
}
}
private string GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.Append("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.Append("<ipVersion>v4</ipVersion>");
sb.Append("<addressingType>dynamic</addressingType>");
sb.Append("<ipAddress>172.2.62.49</ipAddress>");
sb.Append("<subnetMask>255.255.255.0</subnetMask>");
sb.Append("<DefaultGateway>");
sb.Append("<ipAddress>172.2.62.1</ipAddress>");
sb.Append("</DefaultGateway>");
sb.Append("<PrimaryDNS>");
sb.Append("<ipAddress>0.0.0.0</ipAddress>");
sb.Append("</PrimaryDNS>");
sb.Append("</IPAddress> ");
return sb.ToString();
}
But does not work. Am I making an obvious error?
Try this.
If you're using admin/12345.
I made this to write the temperature overlay to my hikvision camera.
Your xml code is definitely correct. I'm not 100% you would need to declare the port number, I know I always had too.
SendToHikVision("admin", "12345", "192.0.0.64", "*The Port You're Using");
void SendToHikVision(string UserName, string Password, string IP, string Port)
{
try
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + IP + ":" + Port + "/Network/interfaces/1/");
wr.Accept = "*/*";
wr.Method = "PUT";
wr.ReadWriteTimeout = 5000;
wr.Credentials = new NetworkCredential(UserName, Password);
byte[] pBytes = GetDHCPPost();
wr.ContentLength = pBytes.Length;
using (Stream DS = wr.GetRequestStream())
{
DS.Write(pBytes, 0, pBytes.Length);
DS.Close();
}
wr.BeginGetResponse(r => { var reponse = wr.EndGetResponse(r); }, null);
}
catch { }
}
byte[] GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.AppendLine("<ipVersion>v4</ipVersion>");
sb.AppendLine("<addressingType>dynamic</addressingType>");
sb.AppendLine("<ipAddress>172.2.62.49</ipAddress>");
sb.AppendLine("<subnetMask>255.255.255.0</subnetMask>");
sb.AppendLine("<DefaultGateway>");
sb.AppendLine("<ipAddress>172.2.62.1</ipAddress>");
sb.AppendLine("</DefaultGateway>");
sb.AppendLine("<PrimaryDNS>");
sb.AppendLine("<ipAddress>0.0.0.0</ipAddress>");
sb.AppendLine("</PrimaryDNS>");
sb.AppendLine("</IPAddress> ");
return Encoding.ASCII.GetBytes(sb.ToString());
}

Exe destroys itself

I have made an console app (exe) with C#. Application is used to send some http requests to server. It sends json to call server's API to execute some work. I save cookies in environmental variable.
We have noticed some weird behavior with this exe. With some sequence(we were not able to find out what sequence this is) of API calls ( api is called by command line arguments) the exe destroys itself. Its size becomes 0KB from starting 15MB. I have never seen that kind of behavior before. Do you have any idea what could it be?
This is the main part of code that creates http request, and other uploads file...
static public JObject UploadFile(string fileName)
{
HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create(serverDomain + directory + "/File");
string boundaryString = "----SomeRandomText";
requestToServer.AllowWriteStreamBuffering = false;
requestToServer.Method = WebRequestMethods.Http.Post;
requestToServer.ContentType = "multipart/form-data; boundary=" + boundaryString;
requestToServer.KeepAlive = false;
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(serverDomain), new Cookie("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString()));
requestToServer.CookieContainer = cookies;
}
ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
string myFileDescriptionContentDisposition = String.Format(
"Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"myFileDescription",
"A sample file description");
byte[] myFileDescriptionContentDispositionBytes = ascii.GetBytes(myFileDescriptionContentDisposition);
string fileUrl = fileName;
string myFileContentDisposition = String.Format(
"Content-Disposition: form-data;name=\"{0}\"; " + "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
"myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes = ascii.GetBytes(myFileContentDisposition);
FileInfo fileInfo = new FileInfo(fileUrl);
long totalRequestBodySize = boundaryStringLineBytes.Length * 2 + lastBoundaryStringLineBytes.Length + myFileDescriptionContentDispositionBytes.Length + myFileContentDispositionBytes.Length + fileInfo.Length;
requestToServer.ContentLength = totalRequestBodySize;
using (Stream s = requestToServer.GetRequestStream())
{
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileDescriptionContentDispositionBytes, 0,
myFileDescriptionContentDisposition.Length);
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileContentDispositionBytes, 0,
myFileContentDispositionBytes.Length);
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, bytesRead);
}
fileStream.Close();
s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
}
WebResponse response = requestToServer.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
JObject jsonResult = JObject.Parse(replyFromServer);
//CreateErrorLog(replyFromServer);
CreateResponse(replyFromServer);
return jsonResult;
}
static public JObject request(string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serverDomain + directory + "/json.rpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = new CookieContainer();
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(serverDomain), new Cookie("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString()));
httpWebRequest.CookieContainer = cookies;
httpWebRequest.Headers.Add("dopinus.e2.session", Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User).ToString());
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) == null)
{
foreach (Cookie cook in httpResponse.Cookies)
{
Environment.SetEnvironmentVariable(cook.Name, cook.Value, EnvironmentVariableTarget.User);
}
}
else if (Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User) != null)
{
foreach (Cookie cook in httpResponse.Cookies)
{
if (cook.Name == "dopinus.e2.session" && cook.Value != Environment.GetEnvironmentVariable("dopinus.e2.session", EnvironmentVariableTarget.User))
{
Environment.SetEnvironmentVariable(cook.Name, cook.Value, EnvironmentVariableTarget.User);
}
}
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JObject jsonResult = JObject.Parse(result);
//CreateErrorLog(result);
CreateResponse(result);
return jsonResult;
}
}
}

Box-api file upload timeout

I have been fighting with this upload problem for a couple of days and searched the forum for a good answer but have not seen it yet. I am using asp.net and I am currently receiving a timeout when I try to post a file to upload. I have taken the MultipartWebRequest class from the V1 C# Api and changed it(i believe to be correctly but it may be my problem) to work with my program.
public sealed class MultipartWebRequest
{
public string AcceptCharset { get; set; }
public string AcceptEncoding { get; set; }
public string Url { get; set; }
public string Boundary { get; set; }
public string ApiKey { get; private set; }
public string Token { get; private set; }
public MultipartWebRequest(string apiKey, string token, string submitUrl,string acceptCharset = "ISO-8859-1", string acceptEncoding = "gzip,deflate" )
{
Boundary = "----------------" + DateTime.Now.Ticks;
ApiKey = apiKey;
Token = token;
Url = submitUrl;
AcceptCharset = acceptCharset;
AcceptEncoding = acceptEncoding;
}
public string SubmitFiles(
//string[] filePaths,
UploadableFile[] files,
bool isShared,
string message,
string[] emailsToNotify,
string folderId)
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
if (files != null)
{
buffer = AssembleFilesBlock(files, folderId);
resultStream.Write(buffer, 0, buffer.Length);
}
if (!string.IsNullOrEmpty(message))
{
buffer = AssembleMessageBlock(message);
resultStream.Write(buffer, 0, buffer.Length);
}
//buffer = AssembleSharedBlock(isShared);
//resultStream.Write(buffer, 0, buffer.Length);
if (emailsToNotify != null)
{
buffer = AssembleEmailsBlock(emailsToNotify);
resultStream.Write(buffer, 0, buffer.Length);
}
buffer = GetFormattedBoundary(true);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
HttpWebRequest myRequest = CreateRequest(buffer.Length);
using (Stream stream = myRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
string response;
using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse())
using (Stream responseStream = myHttpWebResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
response = reader.ReadToEnd();
responseStream.Close();
}
myHttpWebResponse.Close();
return response;
}
private byte[] GetFormattedBoundary(bool isEndBoundary)
{
string template = isEndBoundary ? "--{0}--{1}" : "--{0}{1}";
return Encoding.ASCII.GetBytes(string.Format(template, Boundary, Environment.NewLine));
}
private byte[] AssembleEmailsBlock(string[] emailsToNotify)
{
return new byte[1];
}
private byte[] AssembleSharedBlock(bool isShared)
{
byte[] boundaryContent = GetFormattedBoundary(false);
return new byte[1];
}
private byte[] AssembleMessageBlock(string message)
{
return new byte[1];
}
private byte[] AssembleFilesBlock(UploadableFile[] files, string folderId)
{
byte[] buffer = null;
using (MemoryStream resultStream = new MemoryStream())
{
for (int i = 0; i < files.Length ; i++)
{
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleFile(files[i]);
resultStream.Write(buffer, 0, buffer.Length);
}
buffer = GetFormattedBoundary(false);
resultStream.Write(buffer, 0, buffer.Length);
buffer = AssembleStringValue("folder_id", folderId);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private byte[] AssembleStringValue(string paramName, string paramValue)
{
StringBuilder result = new StringBuilder();
result.AppendFormat("Content-Disposition: form-data; name=\"{0}\"{1}", paramName, Environment.NewLine);
result.AppendLine();
result.AppendLine(paramValue);
return Encoding.ASCII.GetBytes(result.ToString());
}
private byte[] AssembleFile(UploadableFile file)
{
byte[] buffer;
using (MemoryStream resultStream = new MemoryStream())
{
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", Guid.NewGuid(), file.FileName, Environment.NewLine));
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes("Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(file.FileContents);
//buffer = File.ReadAllBytes(filePath);
resultStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
resultStream.Write(buffer, 0, buffer.Length);
resultStream.Flush();
buffer = resultStream.ToArray();
}
return buffer;
}
private HttpWebRequest CreateRequest(long contentLength)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Method = "POST";
//webRequest.AllowWriteStreamBuffering = true;
webRequest.ContentType = string.Concat("multipart/form-data;boundary=", Boundary);
webRequest.Headers.Add("Authorization", "BoxAuth api_key=" + ApiKey + "&auth_token=" + Token);
webRequest.Headers.Add("Accept-Encoding", AcceptEncoding);
webRequest.Headers.Add("Accept-Charset", AcceptCharset);
webRequest.ContentLength = contentLength;
webRequest.ServicePoint.ConnectionLeaseTimeout = 0;
return webRequest;
}
}
Here is my default asp.net page... This is mainly just a testing page. And I can to GET requests and login and get the token and folders and everything else.
public partial class _Default : System.Web.UI.Page
{
public const string APIKEY = "{APIKEY}";
public const string AUTH_STRING = "https://www.box.com/api/1.0/auth/";
public const string GET_TOKEN_STRING = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key={0}&ticket={1}";
public const string BASE_URL = "https://api.box.com/2.0/";
public string ticket = "";
public string token = "";
public string login = "";
public BoxUser boxUser;
HttpContext http;
protected void Page_Load(object sender, EventArgs e)
{
http = HttpContext.Current;
ticket = http.Request["ticket"];
token = http.Request["auth_token"];
login = http.Request["login"];
}
protected void btnBoxLogin_Click(object sender, EventArgs e)
{
string bURL = "https://www.box.com/api/1.0/rest?action=get_ticket&api_key=" + APIKEY;
HttpWebRequest wGetUrl = (HttpWebRequest)WebRequest.Create(bURL);
wGetUrl.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = wGetUrl.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
if (reader != null)
{
string xmlString = "";
string tmpString = reader.ReadLine();
while (tmpString != null)
{
xmlString += tmpString;
tmpString = reader.ReadLine();
}
//txtResponse.Text = xmlString;
GetResponseTicket(xmlString);
}
if(ticket != "")
txtResponse.Text = "\nThe Ticket returned is: " + ticket;
response.Close();
stream.Close();
Response.Redirect(AUTH_STRING + ticket, false);
}
protected void btnGetAuthToken_Click(object sender, EventArgs e)
{
string bURL = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key="+APIKEY+"&ticket=" + ticket;
HttpWebRequest wGetUrl = (HttpWebRequest)WebRequest.Create(bURL);
wGetUrl.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = wGetUrl.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
if (reader != null)
{
string xmlString = "";
string tmpString = reader.ReadLine();
while (tmpString != null)
{
xmlString += tmpString;
tmpString = reader.ReadLine();
}
//txtResponse.Text = xmlString;
GetResponseUser(xmlString);
}
//txtResponse.Text += token + "\n";
//txtResponse.Text += login;
response.Close();
reader.Close();
stream.Close();
}
protected void btnGetUserFolderInfo_Click(object sender, EventArgs e)
{
string usersUrl = "folders/0/items";
string url = BASE_URL + usersUrl;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.ServicePoint.ConnectionLeaseTimeout = 0;
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
JavaScriptSerializer js = new JavaScriptSerializer();
object o = js.DeserializeObject(reader.ReadLine());
if (reader != null)
{
string txt = reader.ReadLine();
txtResponse.Text += "\n" + txt;
while (!reader.EndOfStream)
{
txt = reader.ReadToEnd();
txtResponse.Text += "\n" + txt;
}
}
stream.Close();
response.Close();
reader.Close();
}
private void GetResponseTicket(string xmlString)
{
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("status");
string status = reader.ReadElementContentAsString();
if (status != null && status == "get_ticket_ok")
{
ticket = reader.ReadElementContentAsString();
if (String.IsNullOrEmpty(ticket))
throw new Exception("Ticket was empty");
}
else
throw new Exception("For some reason Status was null or not right");
}
}
private void GetResponseUser(string xmlString)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNode root = doc.DocumentElement;
XmlNode user = root.LastChild;
//XmlNamespaceManager xmlns = new XmlNamespaceManager(doc.NameTable);
//XmlNode node = root.SelectSingleNode(login).InnerText
string login = user.SelectSingleNode("login").InnerText;
string email = user.SelectSingleNode("email").InnerText;
string access_id = user.SelectSingleNode("access_id").InnerText;
string user_id = user.SelectSingleNode("user_id").InnerText;
long space_amount = long.Parse(user.SelectSingleNode("space_amount").InnerText);
long space_used = long.Parse(user.SelectSingleNode("space_used").InnerText);
long max_upload_size = long.Parse(user.SelectSingleNode("max_upload_size").InnerText);
boxUser = new BoxUser(login, email, access_id, user_id, space_amount, space_used, max_upload_size);
}
protected void CreateNewFolder_Click(object sender, EventArgs e)
{
string url = BASE_URL + "folders/389813359";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.Method = "POST";
request.ServicePoint.ConnectionLeaseTimeout = 0;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "{\"name\":\"" + txtNewFolderName.Text+"\"}";
byte[] data = encoding.GetBytes(postData);
using (Stream datastream = request.GetRequestStream())
{
datastream.Write(data, 0, data.Length);
datastream.Close();
}
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
lblResult.Text = responseFromServer;
reader.Close();
stream.Close();
response.Close();
}
protected void UploadNewFile_Click(object sender, EventArgs e)
{
//string url = BASE_URL + "files/data";
string url = "https://upload.box.com/api/2.0/" + "files/data";
//string url = "https://upload.box.com/api/1.0/upload" + token + "/0";
/*string boundary = "----------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
string propFormat = "--" + boundary + newLine + "Content-Disposition: form-data; {0}={1}" + newLine;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Headers.Add("Authorization", "BoxAuth api_key=" + APIKEY + "&auth_token=" + token);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data; boundary=" + boundary;
string fileName = fileUpload.FileName;
byte[] file = fileUpload.FileBytes;
using (Stream stream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(stream);
string tmp = String.Format(propFormat, fileName, file);
writer.Write(tmp);
tmp = String.Format(propFormat, "folder_id", "389813359");
writer.Write(tmp);
writer.Write("--" + boundary + "--");
writer.Flush();
}
WebResponse response = request.GetResponse();
using (Stream resStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(resStream);
lblResult.Text = reader.ReadToEnd();
}*/
Stream stream = fileUpload.PostedFile.InputStream;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
UploadableFile file = new UploadableFile(fileUpload.FileName, text, ".txt");
UploadableFile[] files = new UploadableFile[1];
files[0] = new UploadableFile(fileUpload.FileName, text, ".txt"); ;
MultipartWebRequest myRequest = new MultipartWebRequest(APIKEY,token,url);
string response = myRequest.SubmitFiles(files, false, null, new string[] { }, "0");
txtResponse.Text = response;
}
}
As you can see I have tried all of the different upload urls that I have found around the site. And with all the different ones, not sure exactly which one to use, but doc appears to be the latest "most" correct one? Any help with this would be greatly appreciated as I am fairly new (but understand) to post requests in C#, but VERY new (never done one) to multipart forms in C# (or really anywhere).
The current recommended URL for the API (including file uploads) appears to now be https://api.box.com/2.0. Have you tried using that base URL?

TCPClient seems to not maintain a keep-alive connection, why?

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.

Categories