Upload Image From iPhone to WCF Service - c#

I'm trying to build an iPhone app and c# WCF Service to upload an image to a SQL Service database.
I've got my app breaking an image down to NSData and posting off to a WCF Service using the following code:
NSData *imageData = UIImageJPEGRepresentation(self.image, 90);
NSURL *url = [NSURL URLWithString:#"http://example.com/ImageDiaryService.svc/json/AddMediaItem"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Test" forKey:#"Name"];
[request setPostValue:#"Test description." forKey:#"Description"];
[request setPostValue:#"JPEG" forKey:#"ImageType"];
[request setPostValue:#"iPhone" forKey:#"MediaType"];
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"ImageData"];
[request setDidFinishSelector:#selector(uploadFinished:)];
[request setDidFailSelector:#selector(uploadFailed:)];
[request setDelegate:self];
[request startAsynchronous];
The problem I'm having is with the web service. I'm not sure what type of data I should be receiving from the app POST. I've tried receiving it as an a byte array but that didn't working.
My WCF Service is a REST service.
Any help is much appreciated.

Try receiving it as a Stream. The blog post at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx shows how to receive arbitrary data in a WCF REST service.

Related

Converting a WCF (svcutil) C# code into the corresponding SOAP envelope POST request

This is how I'm currently (and successfully) connecting to a WCF web service in C#. I do not have any control over this web service as it's not developed by me, so I cannot change it. Here is the C# code I use:
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Message.NegotiateServiceCredential = true;
binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
binding.Security.Message.EstablishSecurityContext = true;
EndpointAddress endpoint = new EndpointAddress("<address>");
fooClient client = new fooClient(binding, endpoint);
client.ClientCredentials.UserName.UserName = "the_username";
client.ClientCredentials.UserName.Password = "the_password";
//fooClient class came from running
// svcutil.exe https://<thedomain>/foo/foo.svc?wsdl
//I now work with fooClient, call methods on it, etc.
I want to connect to the web service without C# - by manually creating a SOAP envelope and doing a POST request on the endpoint. I tried doing a POST request that looks like this:
POST /foo/foo.svc HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8
Host: <thedomain>
Connection: close
User-Agent: <my user agent>
Content-Length: 416
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<someWebServiceFunction xmlns="http://<thedomain>/foo/foo">
<someParameter>some parameter value</someParameter>
</someWebServiceFunction>
</soap12:Body>
</soap12:Envelope>
But this does not work because the credentials are missing. (I get an error back: "BadContextToken", "The security context token is expired or is not valid. The message was not processed.")
My question is, how do I add credentials to my SOAP envelope / HTTP request? I tried doing plain HTTP Basic Auth (in the Authorization HTTP header), but this continues to give me the same "BadContextToken" error.
There are two simple ways to trouble shoot your issue:
If you are using Visual Studio, in debug, send the request and intercept what is the detailed content in the request, and you can simulate it using plain HTTP POST.
If you can use SoapUI, you can target the service using SoapUI and send one working request, in the raw tab, you will see what's the accepted request with credentials.

Add header to response of socket in C#

I'm trying to exchange data between a web page and a c# socket.
The c# socket is running on the localhost.
The webpage runs on a server and points to the localhost.
When the webpage sends a Get request to the c# socket an cross-domain error is shown.
XMLHttpRequest cannot load http://localhost:12345/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.3:9000' is therefore not allowed access.
This is the JS running on the web page (Angular).
var serviceUrl = 'http://localhost:12345';
var service = $resource(
serviceUrl,{}, {
getCard: {
method: "GET"
}
}
);
service.getCard();
This is a part of the code from the c# console application.
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend( byteData
, 0
, byteData.Length
, 0
, new AsyncCallback(SendCallback)
, handler
);
How can i add header information to the response.
The headers must be: Access-Control-Allow-Origin: *
It doesnt work when i add it in front of the string.
The header has to be added when you serve the page, not from the socket response. It's just a plain old HTTP header.
If you use IIS to serve your web page, do something like this before sending the page:
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

Url Params not accepting lengthy strings

While sending the image to Web server along with data it is not accepting the lengthy strings. I am sending the data through url. its working good with smaller strings for country,continent and city
http://user.co/UserImage.svc/InsertObjectImage?UserId={UserId}&CategoryId={CategoryId}&ImageName={ImageName}&Gender={Gender}&Continent={Continent}&Country={Country}&City={City}
The above url am using in program upto "?", after that it is with params
NSString *url=[NSString stringWithFormat:#"http://userdata.co.in/UserImage.svc/InsertFacialImage?%#",requestString];
NSLog(#"insert facial image url : %#",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
The code I am using to send the image along with data.Here am passing strings with url.Objective-C NSString can hold the data up to 4.2Billion characters. In the web server the I made it to allow 200 characters for param. But when I am sending the lengthy string like united states of america its making the trouble not storing the data.Services developed in WCF using C#
There are length limitations to URLs but it is also worth checking that your URL is valid.
URLs need to be correctly encoded so you should be passing united%20states%20of%20america in your URL string rather than united states of america.
This is because URL encodes spaces to %20. For any other "special" characters these are also encoded. There are many online resource that should help you and a quick online encoder / decoder can be found here: http://meyerweb.com/eric/tools/dencoder/

How do I send an Image to a web services that takes Stream.IO from iOS?

This is the web services function I wan't to call (JSON).
string UploadFileContent(Stream content,string uploadFileId)
Stream description.
How do a send an UIImage (Base64 encoded, or NSInputStream) using NSMutableRequest? Iam using Objective-C (ARC).
To get your image in base64 on a NSString, you can do :
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64Encoding];
After, you can send your request as a string. You can see an example here.

How to Post values from iPhone using ASIHttp?

I want to send some values from my iPhone application to an ASp.Net web page in server. I am using asihttp for that. Its processing the request and invoking the page on server. But the none of the values are retrieved in server side. Below is the code from iPhone app.
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:#"abc" forKey:#"from"];
[request setPostValue:#"abc" forKey:#"name"];
[request setPostValue:#"abc" forKey:#"phone"];
[request setDelegate:self];
[request startSynchronous];
On Server side I am using asp.net c#. THis is the code using for retriving values. But I am getting emtpy string?
sendMail(Request.QueryString["name"],Request.QueryString["from"],Request.QueryString["phone"]);
Could Someone help Please?
I don't think Request.QueryString["name"] will retrieve a post parameter. You either need to change your ASIHttpRequest to include the parameters in the query string, or modify your ASP.NET code to expect post parameters.
You could try Request.Form["name"], Request.Form["phone"], etc. on the server side.
Or, you could try:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#?name=%#&...",urlString,name,...];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
on the client side.
QueryString is for values in the URL. A post will have values in Request.Form or just Request which will search through QueryString & Form for the values.
Another question with more detail about QueryString vs Form.
Request["key"] vs Request.Params["key"] vs Request.QueryString["key"]

Categories

Resources