Consuming WCF with Xamarin form, completed args is null - wcf

I'm trying to consume a WCF Service in my xamarin forms app but I think I've a problem with my CompletedEventArgs because I've got a null object reference error (in the catch).
Here's my code :
private void callWCF()
{
try
{
ServiceRandom req = new ServiceRandom ();
req.InsertUserDetailsCompleted += req_InsertCompleted;
ProspectDetails prospectDetails = new ProspectDetails();
prospectDetails.Nom = "Test insertion appl";
req.InsertUserDetailsAsync(prospectDetails);
Test.Text = "ok";
}
catch (Exception ex)
{
Test.Text = ex.Message;
}
}
private void req_InsertCompleted(object sender, InsertUserDetailsCompletedEventArgs args)
{
string str = args.Result;
throw new NotImplementedException();
}

Related

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

CommunicationException in WCF Service

My problem is that AddExcursionAsync doesn't work, it shows CommunicationException.
In Console application this code works well. But in Silverlight it makes error. Functions
AddListOgTourNumbersAsync and GetListOfTourNumberAsync work correctly. Where I did the error?
Code:
private AdminServiceClient client;
public AddExcursionDialog()
{
InitializeComponent();
DurationElement.Value = new DateTime();
client = new AdminServiceClient();
client.GetListOfTourNumberCompleted += new EventHandler<GetListOfTourNumberCompletedEventArgs>(GetListOfTourNumber);
client.AddListOgTourNumbersCompleted += new EventHandler<AsyncCompletedEventArgs>(AddListOfTourNumbers);
client.AddExcursionCompleted += new EventHandler<AsyncCompletedEventArgs>(AddExcursion);
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
excursion = new Excursion();
excursion.Name = NameText.Text;
excursion.Cost = Convert.ToDouble(CostText.Text);
excursion.Place = PlaceText.Text;
excursion.Duration= (DateTime)DurationElement.Value;
excursion.Agency_id = tour_names[AgencyCB.SelectedValue.ToString()];
excursion.MaxPpl = Convert.ToInt32(MaxPplText.Text);
client.GetListOfTourNumberAsync();
client.AddExcursionAsync(excursion);
client.AddListOgTourNumbersAsync(tour_id, excursion.NumberOfList);
this.DialogResult = true;
}
I have also battled with CommunicationException(s). At that point, I believe the network were experiencing regular problems.
In my scenario I had to stabilise this call with a retry algorithm.
I'm not saying you should do this all the time, but use it to test.
In this code, the exception is allowed to be thrown if the 3rd attempt fails.
string[] Images64;
try { /* 1st try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
try { /* 2nd try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
try { /* 3rd try */
Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
}
catch (CommunicationException) {
throw;
}
}
}

Implementation of simple Java IDE using Runtime Process and JTextArea

I am developing a simple Java IDE like Netbeans/Eclipse. My GUI includes two JTextArea component, one used as a TextEditor where the end user can type in his programs and the other used as an output window.
I am running the users programs by invoking the windows command prompt through Java Runtime and Process classes. I am also catching the IO streams of the process using the methods getInputStream(), getErrorStream(), getOutputStream().
If the program contains only the statements to print something onto the screen, I am able to display the output on the output window(JTextArea). But if it includes statements to read input from the user, then it must be possible for the user to type the expected input value via the output window and it must be sent to the process just as in Netbeans/Eclipse.
I also checked the following link
java: work with stdin/stdout of process in same time
Using this code, I am able to display only the statements waiting for input and not simple output statements. Also, only a single line is displayed on the output window at a time.
It would be great if anybody can help me to resolve this issue.
Thanks
Haleema
I've found the solution with little modification to the earlier post java: work with stdin/stdout of process in same time
class RunFile implements Runnable{
public Thread program = null;
public Process process = null;
private JTextArea console;
private String fn;
public RunFile(JTextArea cons,String filename){
console = cons;
fn=filename;
program = new Thread(this);
program.start();
}
#Override
public void run() {
try {
String commandj[] = new String[4];
commandj[0] = "cmd";
commandj[1]="/C";
commandj[2]="java";
commandj[3] = fn;
String envp[] = new String[1];
envp[0]="path=C:/Program Files (x86)/Java/jdk1.6.0/bin";
File dir = new File("Path to File");
Runtime rt = Runtime.getRuntime();
process = rt.exec(commandj,envp,dir);
ReadStdout read = new ReadStdout(process,console);
WriteStdin write = new WriteStdin(process, console);
int x=process.waitFor();
console.append("\nExit value: " + process.exitValue() + "\n");
}
catch (InterruptedException e) {}
catch (IOException e1) {}
}
}
class WriteStdin implements Runnable{
private Process process = null;
private JTextArea console = null;
public Thread write = null;
private String input = null;
private BufferedWriter writer = null;
public WriteStdin(Process p, JTextArea t){
process = p;
console = t;
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
write = new Thread(this);
write.start();
console.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent e){
//save the last lines for console to variable input
if(e.getKeyChar() == '\n'){
try {
int line = console.getLineCount() -2;
int start = console.getLineStartOffset(line);
int end = console.getLineEndOffset(line);
input = console.getText(start, end - start);
write.resume();
} catch (BadLocationException e1) {}
}
}
});
console.addCaretListener(new javax.swing.event.CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
console.setCaretPosition(console.getDocument().getLength());
throw new UnsupportedOperationException("Not supported yet.");
}
});
console.addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent e)
{
console.setCaretPosition(console.getDocument().getLength());
}
});
}
#Override
public void run(){
write.suspend();
while(true){
try {
//send variable input in stdin of process
writer.write(input);
writer.flush();
} catch (IOException e) {}
write.suspend();
}
}
}
class ReadStdout implements Runnable{
public Thread read = null;
private BufferedReader reader = null;
private Process process = null;
private JTextArea console = null;
public ReadStdout(Process p,JTextArea t){
process = p;
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
console = t;
read = new Thread(this);
read.start();
}
public void run() {
String line;
try {
while((line = reader.readLine())!=null)
console.append(line+"\n");
}catch (IOException e) {}
}
}

Monotouch WCF call crashes with SIGILL error on 10th attempt

Using latest monotouch(4.0.3) we have WCF services that are called. After performing the call the 10th attempt crashes. I have created a test program that calls simple WCF call to see if service is up. Responds with an OK message. On 10th call it fails. Tried Server config settings, Close, Dispose on client still same results. Sample Test code segment below:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
mailButton.TouchUpInside += (o, e) =>
{
BasicHttpBinding BindType = new BasicHttpBinding();
BindType.ReceiveTimeout = new TimeSpan(0,0,15);
EndpointAddress ep = new EndpointAddress(#"http://myservice.mydomain.com/MyBusServiceBusService/MFService.svc/BaseService");
BaseServiceClient MFService = new BaseServiceClient(BindType, ep);
MFService.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0,0,10);
MFService.BaseServiceTestCompleted += delegate(object sender, BaseServiceTestCompletedEventArgs ex)
{
UIAlertView alert = new UIAlertView();
alert.Title = "Base Service Test";
alert.AddButton("Ok");
++timesThrough;
alert.Message = ex.Result + " Times=" + timesThrough.ToString();;
alert.InvokeOnMainThread(delegate{alert.Show(); });
var clientObject = sender as BaseServiceClient;
if (clientObject != null && clientObject.State == System.ServiceModel.CommunicationState.Opened)
{
(clientObject.ChannelFactory).Close();
(clientObject).Close();
((IDisposable)clientObject).Dispose();
clientObject = null;
}
if (MFService != null)
{
(MFService.ChannelFactory).Close();
(MFService).Close();
((IDisposable)MFService).Dispose();
MFService = null;
}
GC.Collect();
};
try
{
MFService.BaseServiceTestAsync();
}
catch (Exception ex)
{
UIAlertView alert = new UIAlertView();
alert.Title = "Base Service Test";
alert.AddButton("Ok");
alert.Message = ex.Message ;
alert.InvokeOnMainThread(delegate{alert.Show();});
MFService = null;
GC.Collect();
}
};
}
This issue was fixed in the latest MonoTouch (4.1 beta). The 4.2 (stable) release should be available soon.

java mail keeping Transport object connected

How do i keep the java mail transport object alive or connected.
I have written this in my code in a simple class file inside a web application : -
#Resource(name = "myMailServer")
private Session mailSession;
Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
System.out.println("" + transport.isConnected());
if(!transport.isConnected()) {
transport.connect(username, password);
}
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
the full code here
Now everytime i run this code it takes some time to connect with the mail server
and the line
System.out.println("" + transport.isConnected());
prints a false
How do i retain the object transport as it does gets null and into the block
if(transport == null) {
or the transport object remains connected...
Thanks
Pradyut
the code should be....
with a static initialization of transport object
without any problems but can be good with a function
static Transport getTransport() method
#Resource(name = "myMailServer")
private Session mailSession;
static Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
}
if(!transport.isConnected()) {
transport.connect(username, password);
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
Thanks
Regards
Pradyut