parse xml return after a post method - windows-phone-7

I use post to post parameter to server and get the result in string, how do I parse that result and bind it to listbox? It seems that (for some reason) I can't output the string to textblock or messagebox. For parse xml I use XDocument (which take stream in parameter)
My code following:
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
string post = "track=love";
// post = HttpUtility.UrlEncode(post);
Console.WriteLine(post);
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(post);
// Write to the request stream.
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
//THIS ALWAYS RETURN "" VALUE, EXPECT TO RETURN XML STRING
string str = streamRead.ReadToEnd();
//Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
and I want to use XDocument to parse the data like this:
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("tracks").Elements("item")
select new searchResult
{
artist = (string)query.Element("artist"),
album = (string)query.Element("album"),
track = (string)query.Element("track"),
// artistA = (string)query.Element("artists").Element("artist"),
};
listBox1.ItemsSource = data;
var data1 = from query in xdoc.Descendants("artists").Elements("item")
select new searchResult
{
artistA = (string)query.Element("artist"),
};
listBox2.ItemsSource = data1;

Related

Why am I getting a "NotSupportedException" with this code?

I am trying to call a Web API method from a handheld device (Compact Framework) with this code:
// "fullFilePath" is a value such as "\Program Files\Bla\abc.xml"
// "uri" is something like "http://localhost:28642/api/ControllerName/PostArgsAndXMLFile?serialNum=8675309&siteNum=42"
SendXMLFile(fullFilePath, uri, 500);
. . .
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
uri = uri.Replace('\\', '/');
if (!uri.StartsWith("/"))
{
uri = "/" + uri;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded"; // not "text/xml" correct?
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
Somewhere in SendXMLFile(), it is failing with "NotSupportedException" though... As it's running on a handheld device, I can't put a breakpoint in it and step through it; I could sprinkle a bunch of debug statements throughout (MessageBox.Show()), but I'd rather not do that.
The server code never even reaches the breakpoint I put on the "XDocument doc =" line below:
[Route("api/ControllerName/PostArgsAndXMLFile")]
public void PostArgsAndFile([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
XDocument doc = XDocument.Parse(stringifiedXML);
Is it that the Compact framework can't call a (RESTful) Web API method for some reason? Obviously, the client (handheld/Compact Framework) compiles and runs, it just refuses to actually follow through with the runtime realities of it all.
Does my code require a small alteration for it to fit, or do I need to take a completely different tack?
Web API is not going to be able to handle your body content. You declared it as application/x-form-urlencoded, but it is actually XML formatted and your method signature is expecting it to be a XMLDataContract serialized string.
Instead of using the parameter stringifiedXML, instead, just read the body inside your method..
[Route("api/ControllerName/PostArgsAndXMLFile")]
public async void PostArgsAndFile(string serialNum, string siteNum)
{
XDocument doc = XDocument.Parse(await Request.Content.ReadAsStringAsync());
}
Or event better, use a stream directly.
[Route("api/ControllerName/PostArgsAndXMLFile")]
public async void PostArgsAndFile(string serialNum, string siteNum)
{
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
}
This way, you can put the ContentType on the client back to application/xml as it should be.
Using Darrel's code on the server side (I'm using the second one, the Stream), this works on the Client side:
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ContentType = "application/xml";
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
Which can be called like so:
private void buttonNose_Click(object sender, EventArgs e)
{
String fullFilePath = #"C:\McMurtry\LonesomeDove.XML";
String uri = #"http://localhost:21608/api/inventory/sendxml/ff/gg/42";
SendXMLFile(fullFilePath, uri, 500);
}

HttpWebRequest inside a custom class

I'm trying to make an app for windows phone 7 mango, to parse the content of a website. I managed to write all the code, but it was like a war zone ;). When i tried to rearrange the code in a better way, i start facing a very strange problem.
The problem is when i made a custom class called "MedinetMySchedule" inside my project and use breakpoint to step through this class. I found out that the app steps throught the first method getrequest() then return back to the mainpage for few steps, then returns back to the second methods GetRequestStreamCallback(). This jump to the mainpage leaves me with a string having a value of null to parse. Then it jump back to the third method ReadWebRequestCallback(). This last jump gives me nothing important as the debugg ends and i get nothing on the phone-emulator. The MedinetMySchedule class has the following code:-
namespace WindowsPhonePanoramaApplication1
{
public class MedinetMySchedule
{
//Medinet user url
public string url { get; set; }
public String myresponse;
public void getrequest()
{
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(GetRequestStreamCallback, request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
{
string postData = string.Format("username={0}&password={1}&customer=******&doLogin=Logga+in&language=se", "*****", "******");
// Convert the string into a byte array.
byte[] data = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(data, 0, data.Length);
postStream.Close();
}
//Initiating get response
request.BeginGetResponse(ReadWebRequestCallBack, request);
}
private void ReadWebRequestCallBack(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
WebResponse myResponse = (WebResponse)request.EndGetResponse(asynchronousResult);
Stream encodingStream = myResponse.GetResponseStream();
Encoding encode = Encoding.GetEncoding("iso-8859-1");
using (StreamReader httpwebStreamReader = new StreamReader(encodingStream, encode))
{
myresponse= httpwebStreamReader.ReadToEnd();
}
myResponse.Close();
}
}
}
Here is the code that calls the getrequest() and parses the content:-
MedinetMySchedule mittschema = new MedinetMySchedule();
mittschema.url = "https://medinet.se/cgi-bin/doctor.pl?action=login&customer=saskir&language=se";
mittschema.getrequest();
Dispatcher.BeginInvoke(() => parseResults(mittschema.myresponse));
private void parseResults(string myresponse)
{
if (string.IsNullOrEmpty(myresponse))
{
return;
}
//Initiating a listbox and add item to it
List<MediNetScheme> medinetScheme = new List<MediNetScheme>();
//Using HtmlAgilityPack to parse the HTMLcode from the response
HtmlDocument htdoc = new HtmlDocument();
htdoc.LoadHtml(myresponse);
foreach (HtmlNode table in htdoc.DocumentNode.SelectNodes("//table[#class='list-medium']/tbody[1]/tr[#class]"))
{
//Removing ChildNode
table.ChildNodes.RemoveAt(3);
string itemValue = table.InnerText;
//Changing the parsed date into a DateTime
string d;
DateTime datum = DateTime.Parse(itemValue.Remove(11));
d = datum.ToString("D");
//Adding items to the listbox
medinetScheme.Add(new MediNetScheme() { Datum = d, Sections = itemValue.Remove(0, 15) });
}
MediNetScheme.ItemsSource = medinetScheme;
}
Any ideas why this is happening and how to correct it?
Yours
/Omar
The execution going back and forth is because request.BeginGetRequestStream is asynchronous. Basically, it creates a new thread, and executes in parallel of your main code. Therefore, you end up calling parseResult before you've finished downloading the data. There's many ways to rewrite your code, my favorite is using a callback:
First, change the getRequest method to accept a callback, and store it:
private Action Callback;
public void getrequest(Action callback)
{
this.Callback = callback;
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(GetRequestStreamCallback, request);
}
Then, at the end of ReadWebRequestCallback, invoke this callback:
private void ReadWebRequestCallBack(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
WebResponse myResponse = (WebResponse)request.EndGetResponse(asynchronousResult);
Stream encodingStream = myResponse.GetResponseStream();
Encoding encode = Encoding.GetEncoding("iso-8859-1");
using (StreamReader httpwebStreamReader = new StreamReader(encodingStream, encode))
{
myresponse= httpwebStreamReader.ReadToEnd();
}
myResponse.Close();
this.Callback();
}
Finally, from mainpage, call the getrequest method and tell it to use parseResults as callback:
Action callback = () => Dispatcher.BeginInvoke(() => parseResults(mittschema.myresponse));
mittschema.getrequest(callback);

How to send data using webrequest class method?

In my application I send data to a PHP server. I got code from the msdn website.
void SendPost()
{
var url = "http://www.nuatransmedia.com/ncampaign/mailserver/mail1.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "Hello";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}` void SendPost()
{
var url = "http://www.nuatransmedia.com/ncampaign/mailserver/mail1.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "Hello";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
I got mail. But the body messages not show in my mail. Where did I make a mistake? In my PHP code I use postData variable to get my message.
For simpler HTTP usage the classes at http://mytoolkit.codeplex.com/wikipage?title=Http might help you...
These classes help to HTTP POST files (access via $_FILES["..."]). Also there is a RawData property (byte[]) to set the data directly.
(also GZIP, own timeout, and more is supported)

unable to add cookie to httpwebrequest recieved from the first request in wp7

cookie recieved from first request:
private void PostResponseCallback(IAsyncResult asyncResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Stream content = response.GetResponseStream();
SESSIONID = response.Headers["Set-cookie"].ToString();
if (request != null && response != null)
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(content))
{
string _responseString = reader.ReadToEnd();
ResponseString = _responseString;
reader.Close();
}
}
}
}
Unable to set cookie in second request
public void AccDetialsGetResponse()
{
try
{
//CookieContainer cc1 = new CookieContainer();
CookieCollection collection = new CookieCollection();
SESSIONID = SESSIONID.Replace("; Path=/", "");
Cookie cook = new Cookie();
cook.Name = "cookie";
cook.Value = SESSIONID;
collection.Add(cook);
//cc1.Add(new Uri(strHttpsUrl), cccs);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strHttpsUrl);
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(new Uri(strHttpsUrl), collection);
req.BeginGetRequestStream(AccDetailsPostRequest, req);
}
Kindly provide a solution to the above issue...
It turns out you are better off capturing the cookie store from the first request (like so)
//keep in mind ResponseAndCookies is just a hand rolled obj I used to hold both cookies and the html returned during the response
private ResponseAndCookies ReadResponse(IAsyncResult result)
{
Stream dataStream = null;
HttpWebRequest request = (HttpWebRequest) result.AsyncState;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
var responseAndCookies = new ResponseAndCookies
{CookieContainer = request.CookieContainer, Markup = responseFromServer};
return responseAndCookies;
}
And using this cookie store directly when you create then new request. (instead of manually adding the cookie like you had initially)
public void Checkout(ResponseAndCookies responseAndCookies)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/checkout");
request.ContentType = "application/json";
request.CookieContainer = responseAndCookies.CookieContainer;
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "application/json";
request.BeginGetRequestStream(new AsyncCallback(GetRequest), request);
}
Note- if the cookies you are passing around are HTTP ONLY this is actually the ONLY way to deal with them (in the current release of windows phone 7)

WP7 - POST form with an image

I need to send an image from the Windows Phone 7 to some e-mail addresses.
I use this class to submit text values to a PHP script, wich parses data and sends a formatted e-mail to the addresses.
The problem is that I can't figure out how to send an image to that script, to attach the image to the e-mail. The PHP script can be changed in any way. If I have an Image object, how can I change this class to allow sending images?
public class PostSubmitter
{
public string url { get; set; }
public Dictionary<string, string> parameters { get; set; }
public PostSubmitter() { }
public void Submit()
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Prepare Parameters String
string parametersString = "";
foreach (KeyValuePair<string, string> parameter in parameters)
{
parametersString = parametersString + (parametersString != "" ? "&" : "") + string.Format("{0}={1}", parameter.Key, parameter.Value);
}
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(parametersString);
// Write to the request stream.
postStream.Write(byteArray, 0, parametersString.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
//Action<string> act = new Action<string>(DisplayResponse);
//this.Dispatcher.BeginInvoke(act, responseString);
}
I use the class in this way:
Dictionary<string, string> data = new Dictionary<string, string>()
{
{"nom", nom.Text},
{"cognoms", cognoms.Text},
{"email", email.Text},
{"telefon", telefon.Text}
};
PostSubmitter post = new PostSubmitter() { url = "http://example.com/parserscript.php", parameters = data };
post.Submit();
Thank you very much!
I've converted the above code to the following, I'm sure it will help:
public class PostSubmitter
{
public string url { get; set; }
public Dictionary<string, object> parameters { get; set; }
string boundary = "----------" + DateTime.Now.Ticks.ToString();
public PostSubmitter() { }
public void Submit()
{
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
myRequest.Method = "POST";
myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
writeMultipartObject(postStream, parameters);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
public void writeMultipartObject(Stream stream, object data)
{
StreamWriter writer = new StreamWriter(stream);
if (data != null)
{
foreach (var entry in data as Dictionary<string, object>)
{
WriteEntry(writer, entry.Key, entry.Value);
}
}
writer.Write("--");
writer.Write(boundary);
writer.WriteLine("--");
writer.Flush();
}
private void WriteEntry(StreamWriter writer, string key, object value)
{
if (value != null)
{
writer.Write("--");
writer.WriteLine(boundary);
if (value is byte[])
{
byte[] ba = value as byte[];
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg");
writer.WriteLine(#"Content-Type: application/octet-stream");
//writer.WriteLine(#"Content-Type: image / jpeg");
writer.WriteLine(#"Content-Length: " + ba.Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
output.Write(ba, 0, ba.Length);
output.Flush();
writer.WriteLine();
}
else
{
writer.WriteLine(#"Content-Disposition: form-data; name=""{0}""", key);
writer.WriteLine();
writer.WriteLine(value.ToString());
}
}
}
}
To convert an image from the camera to an byte array I've used the follwing:
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
try
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
foto.Source = image;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(image);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 100);
byteArray = ms.ToArray();
}
}
catch (ArgumentNullException) { /* Nothing */ }
}
And I use the class this way:
Dictionary<string, object> data = new Dictionary<string, object>()
{
{"nom", nom.Text},
{"cognoms", cognoms.Text},
{"email", email.Text},
{"telefon", telefon.Text},
{"comentari", comentari.Text},
{"foto", byteArray},
};
PostSubmitter post = new PostSubmitter() { url = "http://example.com/parserscript.php", parameters = data};
post.Submit();
I don't know if it's the best way to send an image from the phone to a server, but I couldn't find anything, so I made my own class just reading this and that, and it has taken me several days. If anybody wants to improve the code or write any comment will be welcomed.
There are lots of questions/answers on here to help already
e.g.
Post with WebRequest - although i couldn't spot any specifically for photos.
Perhaps the best way is to use something like Hammock on Codeplex - http://hammock.codeplex.com/ - or perhaps something like RESTSharp - http://restsharp.org/ - they provide standard REST POST functions.
e.g. if you look within Hammock, then you'll find others who've posted images direct from the camera to tumblr - see http://hammock.codeplex.com/discussions/235650
The above code works perfect. I just use a different method to convert the file to an array of bytes which works perfect with Audio
public static class FileHelper
{
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
}

Resources