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;
}
}
}
Related
I am transforming an Image into pdf for test purposes.
To ensure that the Image is compatible with the printing process later on, I'm running a quick test print during the upload.
I'm creating a simple Test-PDF with a transformer. When I try to print an image with an incompatible format, the ImageManager of the transformer throws an ImageException, starting in the preloadImage() function:
public ImageInfo preloadImage(String uri, Source src)
throws ImageException, IOException {
Iterator iter = registry.getPreloaderIterator();
while (iter.hasNext()) {
ImagePreloader preloader = (ImagePreloader)iter.next();
ImageInfo info = preloader.preloadImage(uri, src, imageContext);
if (info != null) {
return info;
}
}
throw new ImageException("The file format is not supported. No ImagePreloader found for "
+ uri);
}
throwing it to:
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
throws ImageException, IOException {
//Fetch unique version of the URI and use it for synchronization so we have some sort of
//"row-level" locking instead of "table-level" locking (to use a database analogy).
//The fine locking strategy is necessary since preloading an image is a potentially long
//operation.
if (isInvalidURI(uri)) {
throw new FileNotFoundException("Image not found: " + uri);
}
String lockURI = uri.intern();
synchronized (lockURI) {
ImageInfo info = getImageInfo(uri);
if (info == null) {
try {
Source src = session.needSource(uri);
if (src == null) {
registerInvalidURI(uri);
throw new FileNotFoundException("Image not found: " + uri);
}
info = manager.preloadImage(uri, src);
session.returnSource(uri, src);
} catch (IOException ioe) {
registerInvalidURI(uri);
throw ioe;
} catch (ImageException e) {
registerInvalidURI(uri);
throw e;
}
putImageInfo(info);
}
return info;
}
}
throwing it to :
public ImageInfo getImageInfo(String uri, ImageSessionContext session)
throws ImageException, IOException {
if (getCache() != null) {
return getCache().needImageInfo(uri, session, this);
} else {
return preloadImage(uri, session);
}
}
Finally it gets caught and logged in the ExternalGraphic.class:
/** {#inheritDoc} */
public void bind(PropertyList pList) throws FOPException {
super.bind(pList);
src = pList.get(PR_SRC).getString();
//Additional processing: obtain the image's intrinsic size and baseline information
url = URISpecification.getURL(src);
FOUserAgent userAgent = getUserAgent();
ImageManager manager = userAgent.getFactory().getImageManager();
ImageInfo info = null;
try {
info = manager.getImageInfo(url, userAgent.getImageSessionContext());
} catch (ImageException e) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageError(this, url, e, getLocator());
} catch (FileNotFoundException fnfe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageNotFound(this, url, fnfe, getLocator());
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageIOError(this, url, ioe, getLocator());
}
if (info != null) {
this.intrinsicWidth = info.getSize().getWidthMpt();
this.intrinsicHeight = info.getSize().getHeightMpt();
int baseline = info.getSize().getBaselinePositionFromBottom();
if (baseline != 0) {
this.intrinsicAlignmentAdjust
= FixedLength.getInstance(-baseline);
}
}
}
That way it isn't accessible for me in my code that uses the transformer.
I tried to use a custom ErrorListener, but the transformer only registers fatalErrors to the ErrorListener.
Is there any way to access the Exception and handle it myself without changing the code of the library?
It was easier than I thought. Before I call the transformation I register a costum EventListener to the User Agent of the Fop I'm using. This Listener just stores the Information what kind of Event was triggered, so I can throw an Exception if it's an ImageError.
My Listener:
import org.apache.fop.events.Event;
import org.apache.fop.events.EventListener;
public class ImageErrorListener implements EventListener
{
private String eventKey = "";
private boolean imageError = false;
#Override
public void processEvent(Event event)
{
eventKey = event.getEventKey();
if(eventKey.equals("imageError")) {
imageError = true;
}
}
public String getEventKey()
{
return eventKey;
}
public void setEventKey(String eventKey)
{
this.eventKey = eventKey;
}
public boolean isImageError()
{
return imageError;
}
public void setImageError(boolean imageError)
{
this.imageError = imageError;
}
}
Use of the Listener:
// Start XSLT transformation and FOP processing
ImageErrorListener imageListener = new ImageErrorListener();
fop.getUserAgent().getEventBroadcaster().addEventListener(imageListener);
if (res != null)
{
transformer.transform(xmlDomStreamSource, res);
}
if(imageListener.isImageError()) {
throw new ImageException("");
}
fop is of the type Fop ,xmlDomStreamSource ist the xml-Source I want to transform and res is my SAXResult.
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();
}
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) {}
}
}
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.
In one of the WCF tutorials, I saw the following sample code:
Dim service as ...(a WCF service )
try
..
service.close()
catch ex as Exception()
...
service.abort()
end try
Is this the correct way to ensure that resources (i.e. connections) are released even under error conditions?
See Indisposable: WCF Gotcha #1*, where he comes up with a convenient wrapper method:
public delegate void UseServiceDelegate<T>(T proxy);
public static class Service<T>
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
public static void Use(UseServiceDelegate<T> codeBlock)
{
var proxy = (IClientChannel)_channelFactory.CreateChannel();
var success = false;
try
{
codeBlock((T)proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}
Usage:
Service<IOrderService>.Use(
orderService =>
{
orderService.PlaceOrder(request);
});
* Link removed as it appears to be malicious.
I've had good luck with this model:
Dim service As New MyService()
Dim closed As Boolean = False
Try
service.Open()
If Not service.State = ServiceModel.CommunicationState.Opened Then
''Handle a not-opened state here
End If
service.MyMethod()
service.Close()
closed = true
Catch ex As Exception
''Handle errors here
Finally
If Not closed Then
service.Abort()
End If
End Try
service = Nothing
You've got the general idea correct. I've used the following extension method to keep the lines of repetitive code to a minimum.
public static class ICommunicationObjectExtensions
{
public static void SafelyCloseConnection(this ICommunicationObject objectToClose)
{
bool success = false;
try
{
objectToClose.Close();
success = true;
}
finally
{
if (!success)
{
objectToClose.Abort();
}
}
}
}
Example of code using this extension method:
HelloWorldServiceClient client = new HelloWorldServiceClient();
HelloWorldDataContract dc = new HelloWorldDataContract();
try
{
client.Open();
dc = client.SayHello();
} // Add catch blocks here for anything you want to handle.
finally
{
client.SafelyCloseConnection();
}
Of course this is C#, but I think that should still be of help.
If you use a client side cache, you might consider using Expression Trees (see http://thegrenade.blogspot.com/2009/07/using-expression-trees-for-more-elegant.html):
private static TEntity GetItem<TProxy, TEntity, TIdentity>(Expression<Func<TProxy, TIdentity, TEntity>> expression, TProxy proxy, TIdentity id)
where TEntity : class
where TProxy : ICommunicationObject
{
TEntity item = Cache.GetItem<TEntity, TIdentity>(id);
if (item == null)
{
try
{
var originalDelegate = expression.Compile();
item = originalDelegate.Invoke(proxy, id);
}
finally
{
try{ proxy.Close(); }
finally { proxy.Abort(); }
}
Cache.AddItem<TEntity, TIdentity>(item);
}
return item;
}
Usage:
Product p = GetItem((client, identifier) => client.GetProduct(identifier), new CatalogServiceClient(), 123);