c# Error handling for HttpWebRequest - c#

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

Related

http request put not working with json format

I am trying to call an update api with the given parameter at the end of the url, however the update was unsuccessful and returns me an exception.
Here is my sample code for PUT method:
string result = "";
string json = "{" +
"\"ID\": " + 343336 + ", " +
"\"occurence\": " + 0 + ", " +
"\"user\": " + "Juan Dela Cruz" + ", " +
"\"comments\":" + "Test comments" +
"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://myurl/Update/343336");
request.Method = "PUT";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
console.WriteLine(result);
I already put a try catch on my code and it was returning me this error:
Unrecognized token: was expecting (true, false or null)
Any comments/suggestions TIA.

Error when sending SOAP Request in C# Console Application

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?

C# - Not all code paths return a value

Sorry it's similar to other posts but I've read similar posts for an hour, and reviewed/re-reviewed my code but I just can't see where it does not return a value. Any assistance appreciated.
public static bool UploadLog()
{
var uploader = new BackgroundWorker();
uploader.DoWork += delegate (object sender, DoWorkEventArgs e)
{
Properties.Settings.Default.logUrl = "";
Properties.Settings.Default.Save();
System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
Data["api_paste_expire_Date"] = "N";
Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + #"\Logs\RWC.log");
Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
Data["api_option"] = "paste";
WebClient wb = Proxy.setProxy();
try
{
byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
string response;
using (MemoryStream ms = new MemoryStream(bytes))
using (StreamReader reader = new StreamReader(ms))
response = reader.ReadToEnd();
if (response.StartsWith("Bad API request"))
{
Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
e.Result = false;
}
else
{
Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
Properties.Settings.Default.logUrl = response;
Properties.Settings.Default.Save();
e.Result = true;
}
}
catch (Exception ex)
{
Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
e.Result = false;
}
};
uploader.RunWorkerAsync();
}
Edit: I have already tried running this function as async but it resulted in locking up the UI, hence running this in a background worker.
For a function to return a bool (see function definition), you will have to return one at least somewhere in your code. Add return true; right after uploader.RunWorkerAsync ();. This will do the job.
A better possibility would be to make the function async or to use void as a return type.
You method declaration states a bool return value. public static bool UploadLog(), therefore, all your code paths must return a bool. By code path.... all "exit points" of your method must return a value. Unless you change "bool" to "void" which would simply mean your method does not return a value.
/// <summary>
/// With return bool
/// </summary>
/// <returns></returns>
public static bool UploadLog()
{
var didItWork = true;//here's a return value you could use. Initialize to true
var uploader = new BackgroundWorker();
uploader.DoWork += delegate (object sender, DoWorkEventArgs e)
{
Properties.Settings.Default.logUrl = "";
Properties.Settings.Default.Save();
System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
Data["api_paste_expire_Date"] = "N";
Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + #"\Logs\RWC.log");
Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
Data["api_option"] = "paste";
WebClient wb = Proxy.setProxy();
try
{
byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
string response;
using (MemoryStream ms = new MemoryStream(bytes))
using (StreamReader reader = new StreamReader(ms))
response = reader.ReadToEnd();
if (response.StartsWith("Bad API request"))
{
Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
e.Result = false;
}
else
{
Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
Properties.Settings.Default.logUrl = response;
Properties.Settings.Default.Save();
e.Result = true;
}
}
catch (Exception ex)
{
Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
e.Result = false;
didItWork = false;//did not work, so set the return value accordingly
}
};
uploader.RunWorkerAsync();
return didItWork;//return the result
}
OR
/// <summary>
/// Drop the return value by making it void instead of bool
/// </summary>
public static void UploadLog()
{
var uploader = new BackgroundWorker();
uploader.DoWork += delegate (object sender, DoWorkEventArgs e)
{
Properties.Settings.Default.logUrl = "";
Properties.Settings.Default.Save();
System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
Data["api_paste_expire_Date"] = "N";
Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + #"\Logs\RWC.log");
Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
Data["api_option"] = "paste";
WebClient wb = Proxy.setProxy();
try
{
byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
string response;
using (MemoryStream ms = new MemoryStream(bytes))
using (StreamReader reader = new StreamReader(ms))
response = reader.ReadToEnd();
if (response.StartsWith("Bad API request"))
{
Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
e.Result = false;
}
else
{
Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
Properties.Settings.Default.logUrl = response;
Properties.Settings.Default.Save();
e.Result = true;
}
}
catch (Exception ex)
{
Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
e.Result = false;
didItWork = false;//did not work, so set the return value accordingly
}
};
uploader.RunWorkerAsync();
}
A few comments pointed back to looking at using async instead of a background worker. I read up a bit more on this and revisited my code and it is now working successfully, and not locking up the UI either. :)
My now working code:
public static async Task<bool> UploadLog()
{
Properties.Settings.Default.logUrl = "";
Properties.Settings.Default.Save();
System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
Data["api_paste_expire_Date"] = "N";
Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + #"\Logs\RWC.log");
Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
Data["api_option"] = "paste";
WebClient wb = Proxy.setProxy();
try
{
byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
string response;
using (MemoryStream ms = new MemoryStream(bytes))
using (StreamReader reader = new StreamReader(ms))
response = reader.ReadToEnd();
if (response.StartsWith("Bad API request"))
{
Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
return false;
}
else
{
Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
Properties.Settings.Default.logUrl = response;
Properties.Settings.Default.Save();
return true;
}
}
catch (Exception ex)
{
Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
return true;
}
}
My button to call the code:
private async void btnUpload_Click(object sender, EventArgs e)
{
this.btnUpload.Enabled = false;
this.btnUpload.Text = "Uploading...";
var uploaded = await Task.Run(Pastebin.UploadLog);
this.btnUpload.Text = "Upload";
this.btnUpload.Enabled = true;
if (uploaded == true)
{
Clipboard.SetText(Properties.Settings.Default.logUrl);
MessageBox.Show("Your logfile has been uploaded to Pastebin successfully.\r\n" +
"The URL to the Paste has been copied to your clipboard.", "Upload successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The upload of your logfile to Pastebin failed.", "Upload failed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

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?

Why does WebResponse never end when reading twitter firehose stream?

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

Categories