WebResponse Timeout Error in C# - c#

I am trying to send image using web service. I am converting image first to base64 string and using web request Post method sending to server. Here is my code.
try
{
qry = "Select ProductImage From tbl_Product where ProductOnlineID=0";
dt = db.DataTable(qry);
foreach (DataRow dr in dt.Rows)
{
string fileName = dr["ProductImage"].ToString();
string storeLocation = Application.StartupPath + #"\product_image\";
if (System.IO.File.Exists(storeLocation + fileName))
{
Image image = Image.FromFile(storeLocation + fileName);
MemoryStream m = new MemoryStream();
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
string url_upload_imag = #"http://Myserver/api/offline/json/1.0/index.php";
string rq = "token=" + apikey + #"&json_data={%22method%22:%22uploadProductImagesLocal%22,%22data%22:[{%22imgName%22:%22" + fileName + "%22,%22imgString%22:%22" + base64String + "%22}]}";
WebRequest request = WebRequest.Create(url_upload_imag);
request.Method = "POST";
request.ContentLength = rq.Length;
byte[] array = new UTF8Encoding().GetBytes(rq);
request.ContentType = "application/x-www-form-urlencoded";
using (Stream str = request.GetRequestStream())
{
str.Write(array, 0, array.Length);
using (WebResponse ws = request.GetResponse())
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject_Image));
RootObject_Image obj = (RootObject_Image)jsonSerializer.ReadObject(ws.GetResponseStream());
MessageBox.Show("Done" + fileName + obj.data);
}
}
}
}
}
catch (WebException ex)
{
MessageBox.Show("Error in Sending Image:" + ex.ToString(), "Error:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
My Problem is..When I run the application I get Time out Error..I've tried everything setting timeout to infinite doesn't work for me. My base64 string is also correct.
Web service is created in php. what could be error?? and if there is any error, from which side it could be, PHP or C#?

Related

Http multipart request from windows phone 8 to send an text and an image using C# in WP8

I need make a multipart post request to a Rest service to send an image and a string but I can't do the code work. this is the code and I make a comment with capital letters where I get the exception and the exception message in the catch block.
public async Task<bool> addImages(Project project)
{
bool success = false;
string uuid = project.uuid;
if (uuid.Equals(""))
{
return success;
}
mUploadedImages = 0;
mProject = project;
string service = "service/imagen-project/add";
string serviceURL = mBaseURL + "/pwpcloud/" + service;
//build the REST request
// HTTP web request
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceURL);
httpWebRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
httpWebRequest.Method = "POST";
httpWebRequest.AllowWriteStreamBuffering = false;
//Calculate the total size of the upload content.
string boundaryStringLine = "\r\n--" + boundary + "\r\n";
byte[] boundaryStringLineBytes = Encoding.UTF8.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundary + "--\r\n";
byte[] lastBoundaryStringLineBytes = Encoding.UTF8.GetBytes(lastBoundaryStringLine);
// Get the byte array of the myFileDescription content disposition
string myFileDescriptionContentDisposition = String.Format(
"Content-Dis-data; name=\"{0}\"\r\n\r\n","project");
byte[] myFileDescriptionContentDispositionBytes = Encoding.UTF8.GetBytes(myFileDescriptionContentDisposition);
byte[] uuidBytes = Encoding.UTF8.GetBytes(project.uuid);
string fileUrl = "isostore:/" + project.Name + "_ID" + project.ID + "_Pictures/Pic_1.jpg";
string fileName = project.Name + "_ID" + project.ID + "_Pictures/Pic_1.jpg";
string myFileContentDisposition = String.Format("Content-Dis-data;name=\"{0}\"; " +
"filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", "myFile", Path.GetFileName(fileUrl), "image/png");
byte[] myFileContentDispositionBytes = Encoding.UTF8.GetBytes(myFileContentDisposition);
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
var fileStream = isoStore.OpenFile(fileName, FileMode.Open, FileAccess.Read);
byte[] imageBytes = new byte[fileStream.Length];
// Calculate the total size of the HTTP request
long totalRequestBodySize = boundaryStringLineBytes.Length * 2 + lastBoundaryStringLineBytes.Length + myFileDescriptionContentDispositionBytes.Length + uuidBytes.Length +
+myFileContentDispositionBytes.Length + imageBytes.Length;
httpWebRequest.ContentLength = totalRequestBodySize;
//Set cripted authorization -- WORKS FINE
setAuthorization(httpWebRequest, service, WEBSERVICE_REQUEST_TYPE_POST);
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null))
{
// Send the file description content disposition over to the server
await stream.WriteAsync(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
await stream.WriteAsync(myFileDescriptionContentDispositionBytes, 0, myFileDescriptionContentDisposition.Length);
await stream.WriteAsync(uuidBytes, 0, uuidBytes.Length);
// Send the file content disposition over to the server
await stream.WriteAsync(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
await stream.WriteAsync(myFileContentDispositionBytes, 0, myFileContentDispositionBytes.Length);
fileStream.Read(imageBytes, 0, imageBytes.Length);
await stream.WriteAsync(imageBytes, 0, imageBytes.Length);
fileStream.Close();
// Send the last part of the HTTP request body
await stream.WriteAsync(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
}
try
{
var responseTask = Task.Factory.FromAsync<WebResponse>(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, null);
using (var response = (HttpWebResponse)await responseTask) //I GET THE EXCEPCION HERE (
{
string data;
// Read the response into a Stream object.
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
}
catch (Exception e)
{
string err = e.Message; // err = "The remote server returned an error: NotFound" but the ServiceURL is ok
throw;
}
return success;
}
I could run this in a desktop program using C++ but I couldn't find any class to do it in C# using the same "sctructure". This is the C++ code:
void WebServicesClient::addImages(PW::Project *project){
QString uuid = project->getCloudUUID();
if (uuid.isEmpty()) /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return;
mUploadedImages = 0;
mProject = project;
QNetworkRequest request;
QString serviceURL = mBaseURL+"/service/imagen-project/add";
request.setUrl(QUrl(serviceURL));
// request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"project\""));
textPart.setBody(uuid.toAscii());
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
QString fileName = project->getImages().at(0)->getFileName();
QString header = "form-data; name=\"file\"";
header += "; filename=\"" + fileName + "\"";
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(header));
QFile *file = new QFile(project->getImages().at(0)->getFullPath());
file->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(file);
file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
multiPart->append(textPart);
multiPart->append(imagePart);
setAuthorization(request, "service/imagen-project/add", WEBSERVICE_REQUEST_TYPE_POST);
QObject::connect(mNetwork, SIGNAL(finished(QNetworkReply *)),
this, SLOT(onAddImageFinished(QNetworkReply*)));
emit statusChanged(0, "Uploading " + project->getImages().at(0)->getFileName());
QNetworkReply *reply = mNetwork->post(request,multiPart);
}
I hope someone can help me.
Thanks everyone!

While uploading tracks to soundcloud(422) Unprocessable Entity)

I would like to try upload a mp3 file to my soundcloud account. I have written this code for this job.
WebClient client = new WebClient();
string postData = "client_id=" + "xxxxx"
+ "&client_secret=" + "xxx"
+ "&grant_type=password&username=" + "xxx" //your username
+ "&password=" + "xxx";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
tokenInfo = tokenInfo.Remove(0, tokenInfo.IndexOf("token\":\"") + 8);
string token = tokenInfo.Remove(tokenInfo.IndexOf("\""));
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
request.CookieContainer = new CookieContainer();
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(filePath, "#/" + filePath, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", token);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
}
When I debug this code part. I get (422) Unprocessable Entity error in catch block. Why I get this error? How can solve this problem?
Check the Soundcloud documentation:
http://developers.soundcloud.com/docs#errors
422 - "The request looks alright, but one or more of the parameters looks a little screwy. It's possible that you sent data in the wrong format (e.g. an array where we expected a string)."

Uploading image to imgur causes: The Uri string is too long

im trying to develope C# application that uses Imgur api to upload images.
this is my upload function:
public static string PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Headers["Authorization"] = "Client-ID abd937cc5e11dc9";
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
return responseReader.ReadToEnd();
}
if im uploading small pictures (20kb) all works fine.
but when im uploding bigger images (500kb) i get the error:
Invalid URI: The Uri string is too long.
what can i do?
i succeed to upload large images by dividing the base64 string
this is the working code:
public static string PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
const int MAX_URI_LENGTH = 32766;
string base64img = System.Convert.ToBase64String(imageData);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
}
string uploadRequestString = "key=" + apiKey + "&title=" + "imageTitle" +
"&caption=" + "img" + "&image=" + sb.ToString();
// string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Headers["Authorization"] = "Client-ID abd937cc5e11dc9";
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
return responseReader.ReadToEnd();
}
thanks to all.
They way it works is the image is converted like so: System.Convert.ToBase64String(imageData)
That is added to the URI and sent to the server to be decoded back to an image.
You will not be able to get around this issue with a single URI, as its inherent in imgur's design.
Read this for the maximum length a URI can be: What is the maximum length of a URL in different browsers?

Uploading a file to a web service using POST in C#

The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API

How tosave Image in DataBase Using JSON WebService WP7

I want to save Image in Database with JSON web service .without image data save.
But when send image byte It is not save. How to send or Recive Image with JSon webservie in window phone-7
My Webservice:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Register(string emailID, string pwd, string name, string img)
{
ProfileDL _client = new ProfileDL();
_client.Email = emailID;
_client.Password = pwd;
img = img.Replace(' ', '+');
_client.Firstname = name;
_client.Img = Convert.FromBase64String(img);
_client.saveData();
return "Y";
}
WP7 Code:-
//Convert Image to byte code
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
imageBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
}
void GetRequestStreamCallbackx(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string img = string.Empty;
try
{
img = Convert.ToBase64String(imageBytes);
}
catch { }
// Create the post data
// string postData = "";
var json="";
Dispatcher.BeginInvoke(() => json = "{\"emailID\": " + txtemail.Text.Trim() + ",\"pwd\": " + txtpassword.Text + ",\"name\":" + txtname.Text + ",\"img\": " + img + "}");
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// Add the post data to the web request
try
{
postStream.Write(byteArray, 0, byteArray.Length);
}
catch { }
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
there is any thing wrong in my code. Please Help...
Let me guess: an empty request is being made?
If you just use Dispatcher.BeginInvoke() to set the json variable, it probably will be set after the Encoding.UTF8.GetBytes(json) call!
Try it like this:
void GetRequestStreamCallbackx(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string img = string.Empty;
try
{
img = Convert.ToBase64String(imageBytes);
}
catch { }
// Create the post data
// string postData = "";
var json = "";
Dispatcher.BeginInvoke(() =>
{
json = "{\"emailID\": " + txtemail.Text.Trim() + ",\"pwd\": " + txtpassword.Text + ",\"name\":" + txtname.Text + ",\"img\": " + img + "}";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// Add the post data to the web request
try
{
postStream.Write(byteArray, 0, byteArray.Length);
}
catch { }
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
});
}

Categories