WSDL FaultExceptions not caught - soap

I'm attempting to get FaultExceptions to hit for a WSDL service.
I have attempted the following:
Created a new .Net 7.0 project in Visual studio
Added the WSDL service reference for https://wsaimport.uni-login.dk/wsaimport-v7/ws?WSDL
Called the generated WSDL method hentDataAftalerAsync
Added below code to Program.cs
var binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None), Encoding.UTF8), new HttpsTransportBindingElement { MaxReceivedMessageSize = 104857600 });
var ws10Client = new ServiceReference2.WsaImportPortTypeClient(binding, new EndpointAddress("https://wsaimport.uni-login.dk/wsaimport-v7/ws"));
try
{
var res = await ws10Client.hentDataAftalerAsync(new Credentials() {
wsBrugerid = "randomusername",
wsPassword = "randompassword"
});
// this is reached if credentials are correct
foreach (var item in res.hentDataAftalerResponse1.ToList())
{
Console.WriteLine(item);
}
}
catch(FaultException<AuthentificationError> ex)
{
// Neven hit (I expect this exception on wrong credentials)
Console.WriteLine(ex.Message);
}
catch (FaultException ex)
{
// Never hit
Console.WriteLine(ex.Message);
}
catch (ProtocolException ex)
{
// this exception is hit (but no info about the actual soap fault)
}
catch (Exception ex)
{
// Never hit
Console.WriteLine(ex.Message);
}
I have tested the hentDataAftaler operation in SoapUI, and when the credentials are wrong it does generate a SOAP response with a Fault of authentificationError.
So my question is, why is it not working for me in C#?

Related

Opening a Postgres Connection in Xamarin returns Error While Connecting

I am trying to connect my Android Application to Postgres but seems not to work.
The Exception Message is: Exception while Connecting
This is my Code Behind,
private void Login_Clicked(object sender, EventArgs e)
{
DBInterface<DBLogicInput, DBLogicResult> dbLoginLogic = new DBLoginLogic();
DBLogicInput userInput = new DBLogicInput();
DBLogicResult DBResult = new DBLogicResult();
LoginModel useCredentials = new LoginModel()
{
userName = txtUsername.Text,
passWord = txtPassword.Text
};
userInput[typeof(LoginModel).FullName] = useCredentials;
try
{
DBResult = dbLoginLogic.DoProcess(userInput);
bool userExisting = DBResult.ResultCode != DBLogicResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
if (userExisting)
{
Application.Current.MainPage = new NavigationPage(new IndexPage());
}
else
{
_ = DisplayAlert("Login Error", "User does not exist", "Ok");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This is the Class I created to connect the DB.
public abstract class DBLogic : DBInterface<DBLogicInput, DBLogicResult>
{
public string connectionString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=proyektoNijuan";
public DBLogicResult DoProcess(DBLogicInput inOut)
{
//throw new NotImplementedException();
DBLogicResult result = default(DBLogicResult);
NpgsqlConnection connection = null;
NpgsqlTransaction transaction = null;
try {
connection = new NpgsqlConnection(connectionString);
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
transaction = connection.BeginTransaction();
result = Process(connection, inOut);
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();
} finally {
if (connection != null)
{
connection.Close();
}
}
return result;
}
protected abstract DBLogicResult Process(NpgsqlConnection conn, DBLogicInput InOuT);
}
The error exists after the debugger hits the code connection.Open();.
Should I add a web services to connect the postgres to my android app built in xamarin forms?
I am only a beginner in Xamarin Forms. I am just trying to create a self application. And need a little help for me to learn a new platform in programming.
Thank you and Regards,
How to fix it?
Well, I think I am doing it wrong.
Maybe the Right way to Connect the PostgreSQL is to have a WEB API.
Calling that web API to the Xamarin forms.
I really don't know if it is correct, but I will give it a try.
I will update the correct answer after I finish the development of that WEB API so that other beginners will found this answer helpful.

Azure Mobile Apps Offline Client Throws NotSupportedException on Query

I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
public async Task SyncAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());
Debug.WriteLine("SyncAsync: PUSH/PULL completed.");
}
catch (MobileServicePushFailedException e)
{
Debug.WriteLine("SyncAsync: PUSH failed.");
Debug.WriteLine(e.Message);
}
catch (Exception e)
{
Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
Debug.WriteLine(e.Message);
//Debugger.Break();
}
}
public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
{
try
{
if (syncItems)
{
await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
}
var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];
var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;
IEnumerable<TruckFahrer> items =
await OfflineSyncStoreManager.Instance.TruckFahrerTable
//.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
.ToEnumerableAsync();
// TODO: Because above does not work
items = items.Where(fahrer => fahrer.Imei.Equals(imei));
return new ObservableCollection<TruckFahrer>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
Debugger.Break();
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
Debugger.Break();
}
return null;
}
Thanks for any hint,
Eric
Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)

Propogate errors to UI with Spring 3 MVC / REST

When /api/upload REST endpoint is accessed I have a UploadController that uses a service UploadService to upload a file to an ftp server with org.apache.commons.net.ftp.FTPClient. I would like to be able to send information back to the user if the ftp client was unable to connect or timed out, or successfully sent the file. I have some IOException handling, but I don't know how to turn that around and send it back to the front-end. Any help appreciated, thanks!
public void upload(InputStream inputStream) {
String filename = "file.txt"
client = new FTPClient();
try {
client.connect("ftpsite");
client.login("username", "password");
client.storeFile(filename, inputStream);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (inputStream!= null) {
inputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return null;
}
You should throw a new Exception in your catch statement.
For example, you could create a RequestTimeoutException class:
#ResponseStatus(HttpStatus.REQUEST_TIMEOUT)
public class RequestTimeoutException extends RuntimeException { }
and then throw it when need be:
catch (IOException ioe) {
//do some logging while you're at it
throw new RequestTimeoutException();
}

Android:Restful webservice put method showing response with status 405 Method not allowed

I am getting data by http get through restful webservice hosted on IIS7 but when i am trying to put data i am having problem
MY code for put is as follows:
public Void put(String url, List<NameValuePair> data)
{
String response="";
HttpPut put = new HttpPut(url);
String dataString=data.toString();
HttpClient httpclient = new DefaultHttpClient();
try {
StringEntity entity = new StringEntity(dataString, "UTF-8");
entity.setContentType("x-www-form-urlencoded; charset=UTF-8");
put.setEntity(entity);
HttpResponse httpResponse1 = httpclient.execute(put);
StatusLine statusLine = httpResponse1.getStatusLine();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
The response i am getting is 405 Method not allowed, Can anybody tell me what is the problem?
You just have to uncheck webdave feature from the IIS menu which is in the window's features

linking my applet to a server dirctory to recieve or save a file from there?

I' m looking for a code to save the files created in a applet normally text files i want to save them on a server directory how can i do so.
Here is an example of how to send a String. In fact any Object can be sent this method so long as it's serializable and the same version of the Object exists on both the applet and the servlet.
To send from the applet
public void sendSomeString(String someString) {
ObjectOutputStream request = null;
try {
URL servletURL = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/servletName");
// open the connection
URLConnection con = servletURL.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/octet-stream");
// send the data
request =
new ObjectOutputStream(
new BufferedOutputStream(con.getOutputStream()));
request.writeObject(someString);
request.flush();
// performs the connection
new ObjectInputStream(new BufferedInputStream(con.getInputStream()));
} catch (Exception e) {
System.err.println("" + e);
} finally {
if (request != null) {
try {
request.close();
} catch (Exception e) {
System.err.println("" + e);
};
}
}
}
To retrieve on the server side
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
// get the input stream
ObjectInputStream inputStream = new ObjectInputStream(
new BufferedInputStream(request.getInputStream()));
String someString = (String)inputStream.readObject();
ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(response.getOutputStream()));
oos.flush();
// handle someString....
} catch (SocketException e) {
// ignored, occurs when connection is terminated
} catch (IOException e) {
// ignored, occurs when connection is terminated
} catch (Exception e) {
log.error("Exception", e);
}
}
No one is going to hand you this on a plate. You have to write code in your applet to make a socket connection back to your server and send the data. One way to approach this is to push the data via HTTP, and use a library such as commons-httpclient. That requires your server to handle the appropriate HTTP verb.
There are many other options, and the right one will depend on the fine details of the problem you are trying to solve.