Why does webservice toss null pointer in Xamarin Forms - web-services

I have a Xamarin Forms application, I've added a WCF Web Service, that I'm using in another project. I can create a Soap client for this webservice, with one of the provided endpoints. When I try to access any method on this client it tosses a null pointer without offering any details about the exception.
Has anyone had a similar problem? Are there some permission issues with using Xamarin Forms this way?
HelloWorldResponse res = null;
try {
ServiceReference1.UserServicesSoapClient client = new
UserServicesSoapClient(UserServicesSoapClient.EndpointConfiguration.UserServicesSoap12);
HelloWorldRequest req = new HelloWorldRequest();
res = await client.HelloWorldAsync(req);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
return res;
Thanks,

Related

Setting MTOM-enabled property dynamically in Apache CXF

I'm developing SOAP web service using Apache CXF framework. My web-method returns either binary data or plain XML depending on request parameters. Most of requests return binary data, so I configured CXF to use MTOM in service responses.
But this is not always useful: when XML is returned, caller side expects to get plain text/xml document rather than multipart one. So I'd like my web service to dynamically change its binding.
CXF documentation has following example:
Endpoint ep = ...; // example does not explain how to get it
SOAPBinding binding = (SOAPBinding)ep.getBinding();
binding.setMTOMEnabled(true); // or false
Question: how can I get Endpoint instance?
I'm using Spring annotation #Endpoint for web-service and #PayloadRoot for web-method.
You can use the following code if you are using on server,
you need to add import javax.xml.ws.Endpoint;
HelloWorldImpl implementor = new HelloWorldImpl();
String address = "http://localhost:9000/helloWorld";
Endpoint.publish(address, implementor);
From client side
TestMtomService tms = new TestMtomService(wsdlURL, SERVICE_NAME);
TestMtomPortType port = (TestMtomPortType)tms.getPort(PORT_NAME,TestMtomPortType.class);
Binding binding = ((BindingProvider)port).getBinding();
((SOAPBinding)binding).setMTOMEnabled(true);
Refer
If you are downloaded the cxf bundle, code samples for MTOM Server/Client available on following path
apache-cxf-2.7.2\samples\mtom
I created my own marshalled class extended from org.springframework.oxm.jaxb.Jaxb2Marshaller. Only single method is overriden:
public class Marshaller extends Jaxb2Marshaller {
#Override
public void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException {
if ( disableMtom() ) {
super.marshal(graph, result, null);
} else {
super.marshal(graph, result, mimeContainer);
}
}
private boolean disableMtom() {
return ... // depends on response context
}
}
The disableMtom detects if MTOM is disabled from response context. Web service endpoint takes care to pass this context to marshaller somehow.
By default MTOM is enabled.

RESTEasy Client Proxy Preemptive Basic Authentication

I am using RESTEasy Proxy Framework to call my Rest-Services. I would like to use preemptive authentication with the proxy framework.
Thats my current Code:
public void callSomeService() throws Exception {
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
DefaultHttpClient client = new DefaultHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
USERNAME, PASSWORD);
AuthScope authscope = new AuthScope(AuthScope.ANY_HOST,
AuthScope.ANY_PORT, AuthScope.ANY_REALM);
client.getCredentialsProvider().setCredentials(authscope, credentials);
ApacheHttpClient4Executor executer = new ApacheHttpClient4Executor(client);
dummyResource = ProxyFactory.create(DummyResource.class,
"http://localhost:8888/myapp/rest/", executer);
// Do some calls here
}
When I monitor the traffic of my application, the Rest-Service gets called twice:
First the client receives an 401 Error (UNAUTHORIZED)
In the second request there is the Authorization Header added and everything works
fine.
What I actually want to do is that the Authorization Header is already added in the first request! How can I do that?
I am using RESTEasy 2.3.5! I also read the documentation (http://docs.jboss.org/resteasy/docs/2.3.5.Final/userguide/html_single/index.html#transport_layer) where is an example given for preemptive authentication, which actually doesnt work, because of this code:
BasicScheme basicAuth = new BasicScheme();
authCache.put("com.bluemonkeydiamond.sippycups", basicAuth);
You're right, the example in the documentation does not compile. Try replacing the string "com.bluemonkeydiamond.sippycups" with an instance of HttpHost. The HttpHost class has several constructors so be sure to look at the JavaDocs. The simplest constructor takes a string. For example,
BasicScheme basicAuth = new BasicScheme();
authCache.put(new HttpHost("com.bluemonkeydiamond.sippycups"), basicAuth);

Simplest way to make HTTP request in Spring

In my Spring web application I need to make an HTTP request to a non-RESTful API, and parse the response body back as a String (it's a single-dimension CSV list).
I've used RestTemplate before, but this isn't RESTful and doesn't map nicely on to classes. Whenever I implement something like this 'by hand' (eg using HttpClient) I invariably find out later that Spring has a utility class that makes things much simpler.
Is there anything in Spring that will do this job 'out of the box'?
If you look at the source of RestTemplate you will find that internally it uses
java.net.URL
and
url.openConnection()
that is the standard way in Java to make HTTP calls, so you are safe to use that. If there would be a "HTTP client" utility in spring then the RestTemplate would use that too.
I use the Spring Boot with Spring 4.3 Core inside and found a very simple way to make Http request and read responses by using OkHttpClient. Here is the code
Request request = new Request.Builder().method("PUT", "some your request body")
.url(YOUR_URL)
.build();
OkHttpClient httpClient = new OkHttpClient();
try
{
Response response = httpClient.newBuilder()
.readTimeout(1, TimeUnit.SECONDS)
.build()
.newCall(request)
.execute();
if(response.isSuccessful())
{
// notification about succesful request
}
else
{
// notification about failure request
}
}
catch (IOException e1)
{
// notification about other problems
}

WebRequest.DefaultWebProxy.Credentials is null and WCF service call fails if I'm behind proxy

I'm behind ISA Server Proxy and I need to call a web service. Given its wsdl I've created proxies (using Add Service Reference command) and have tried to call the service, but it raised an exception telling me that proxy authorization is required. After some research I've found a solution to my problem
var webproxy = new WebProxy(new Uri("http://<address>:<port>").ToString(), true, new string[]
{
})
{
Credentials = networkCredentials,
BypassProxyOnLocal = false
};
WebRequest.DefaultWebProxy = webproxy;
After this piece of code I'm able to call web service. But as I've read here by default DefaultWebProxy uses the same settings as set in IE. However WebRequest.DefaultWebProxy.Credentials is null and I'm unable to pass thru the proxy. Why?
I've was also same boat. The last answer on this post helped me.
How do I determine (elegantly) if proxy authentication is required in C# winforms app
Especially.
//HACK: add proxy
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.Proxy = proxy;
req.PreAuthenticate = true;
//HACK: end add proxy

How to have a webmethod POST to an HTTPHandler.ashx file

Summary
How to create an HTTPContext within a webservice? or POST to a Handler.ashx from a webservice?
Background
I have a Cold Fusion web application that uses Forms authentication but somehow achieves Windows authentication with this script:
<cfscript>
ws = CreateObject("webservice", "#qTrim.webServiceName#");
ws.setUsername("#qTrim.trimAcct#");
ws.setPassword("#qTrim.trimpwd#");
wsString=ws.UploadFileCF("#qTrim.webserviceurl#","#objBinaryData#", "#qFiles.Filename#", "Document", "#MetaData#");
</cfscript>
Apparently, the setUsername/setPassword values map to a single Windows domain account and this works in production. (The webservice is written in C# and built with .Net 4.0. and it must be used by this domain account)
I developed a DownloadHandler.ashx which works when POSTed to by a process which is running under this domain account (I have a .Net web client with a button that defines PostBackUrl="~/DownloadHandler.ashx"). This HTTPHandler grabs a few items from the HTTPContext and then calls the above webservice method DownloadFile without problems.
My Problem
Now this ColdFusion app needs to download a file using this webservice. When the CF code POSTs an HTML form to the DownloadHandler.ashx it works - BUT ONLY IF the CF tester is using this Windows domain account. This won't work in production because the CF app supports remote anonymous users through forms authentication.
Question
Not knowing ColdFusion myself, I was thinking of the following changes:
Replicate the above CF technique such that user/pswd can be set the same and have CF invoke the ws.DownloadFile method directly
I think this would require using most of my current HTTPHandler code in my webservice but I cannot think of how to handle the output. When this handler is POSTed to, it prompts for OPEN or Save and works nicely but I'm confused on how I would stream this back from the webservice itself.
The current DownloadFile webmethod communicates with a database product and returns output to this (the current) handler:
Code
namespace WebClient
{
public class DownloadHandler : IHttpHandler
{
ASMXproxy.FileService brokerService;
public void ProcessRequest(HttpContext context)
{
brokerService = new ASMXproxy.FileService();
string recNumber = context.Request.Form["txtRecordNumber"];
brokerService.Url = context.Request.Form["txtURL"];
string trimURL = context.Request.Form["txtFakeURLParm"]; // not a real URL but parms to connect to TRIM
brokerService.Timeout = 9999999;
brokerService.Credentials = System.Net.CredentialCache.DefaultCredentials;
byte[] docContent;
string fileType;
string fileName;
string msgInfo = brokerService.DownloadFile(trimURL, recNumber, out docContent, out fileType, out fileName);
string ContentType = MIMEType.MimeType(fileType);
context.Response.AppendHeader("Content-Length", docContent.Length.ToString());
context.Response.AppendHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
context.Response.ContentType = ContentType;
context.Response.OutputStream.Write(docContent, 0, docContent.Length);
context.Response.OutputStream.Flush();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Assuming your CF site is running on IIS and not Apache or some other web server, this might work:
Put your .cfm file that calls the webservice into its own subfolder on your site. Set the Authentication properties of that folder to use Anonymous Authentication, but set the user identity to the Windows Domain account that successfully calls the webservice (click the Set... button on the dialog shown below and enter the appropriate credentials).