WebClient TimeOut Windows Phone 8 - windows-phone-8

I would like to run a task during the waiting of a web request. If the task finishes before the request can return a response, then I would display a message "The server is taking too long". I'm using a WebClient object, how can I manage the time out?
public Class Result
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
{
try
{
_datamanager = new DataManager();
_datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
_datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);
//HERE I NEED TO RUN A TIMER If the response is too long i would display a message
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
NavigationService.GoBack();
NavigationService.RemoveBackEntry();
}
}
}
}
public Class DataManager
{
public void DownloadXmlData(string uri, string critere = "")
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
client.DownloadStringAsync(new Uri(uri + critere));
}
catch(WebException )
{
throw new WebException(MyExceptionsMessages.Webexception) ;
}
catch (Exception )
{
throw new UnknowException(MyExceptionsMessages.UnknownError);
}
}
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//raise Downloadstringcompleted event if error==null
}
}

You can use BackgroundWorker..
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
// your task to do while webclient is downloading
};
bw.RunWorkerCompleted += (s, e) =>
{
// check whether DownloadStringCompleted is fired or not
// if not, cancel the WebClient's asynchronous call and show your message.
client.CancelAsync();
MessageBox.Show("message");
}
client.DownloadStringAsync(uri);
bw.RunWorkerAsync();

Related

How can I mock RabbitMQClient of io.quarkiverse.rabbitmqclient.RabbitMQClient and write junit for basic send and consume operation?

I'm new to the quarkus framework where I'm writing rabbitmq-client library based on quarkur framework. I'm using io.quarkiverse.rabbitmqclient.RabbitMQClient.
I need to write JUnit for basic send and consume operations, please help me with how can I write junit and mock RabbitMQClient. I'm using the below code to send and consume message.
#ApplicationScoped
public class RabbitMQProducerAdapterImpl extends RabbitMQCongiguration implements RabbitMQProducerAdapter {
#Override
public void sendMessage(String exchange, String routingKey, String messagePayload) throws IOException {
setUpConnectionAndChannel();
channel.basicPublish(exchange, routingKey, null, messagePayload.getBytes(StandardCharsets.UTF_8));
Log.info("message sent succefully: " + messagePayload);
}
}
Here is the RabbitMQCongiguration
#ApplicationScoped
public class RabbitMQCongiguration {
#Inject
private RabbitMQClient rabbitClient;
protected Channel channel;
protected void setUpConnectionAndChannel() {
try {
// create a connection
Connection connection = rabbitClient.connect();
// create a channel
channel = connection.createChannel();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
protected void setupQueueInDirectExchange(String exchangeName, String routingKey, String queueName,
boolean createExchangeQueues) throws IOException {
setUpConnectionAndChannel();
if (createExchangeQueues) {
this.channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);
// declaring a queue for this channel. If queue does not exist,
// it will be created on the server. this line not needed if queue already
// present
this.channel.queueDeclare(queueName, true, false, false, null);
}
// Bind Routing Key to Exchange
this.channel.queueBind(queueName, exchangeName, routingKey);
}
}
Below is the class for consumer
#ApplicationScoped
public class RabbitMQConsumerAdapterImpl extends RabbitMQCongiguration implements RabbitMQConsumerAdapter, Runnable {
private String queueName;
private MessageProcessor messageProcessor;
#Override
public void consumeMessage(String exchange, String queueName, String routingKey,
MessageProcessor messageProcessor) throws IOException {
Log.info("starting consumer...");
try {
this.queueName = queueName;
this.messageProcessor = messageProcessor;
Log.info("setting up rabbitMQPrefetchCountConfig");
setupQueueInDirectExchange(exchange, routingKey, queueName, false);
Thread consumerThread = new Thread(this);
consumerThread.start();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#Override
public void run() {
try {
// start consuming messages. Auto acknowledge messages.
Log.info("Start consuming messages from thread...");
channel.basicConsume(this.queueName, false, (Consumer) new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String msgPayload = null;
if (body == null || body.length == 0) {
Log.warn("Invalid Message Body - Consumer Tag : " + consumerTag + ", Message DeliveryTag : "
+ envelope.getDeliveryTag());
channel.basicReject(envelope.getDeliveryTag(), false);
} else {
msgPayload = new String(body);
try {
JsonParser.parseString(msgPayload);
} catch (JsonSyntaxException ex) {
Log.error(msgPayload + " is not a valid json, Reason - ", ex);
channel.basicReject(envelope.getDeliveryTag(), false);
Log.warn("Rejected the current payload.");
return;
}
messageProcessor.processMessage(msgPayload);
channel.basicAck(envelope.getDeliveryTag(), false);
}
// just print the received message.
Log.info("Received: " + new String(body, StandardCharsets.UTF_8));
}
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#ApplicationScoped
public class MessageProcessorImpl implements MessageProcessor{
#Override
public void processMessage(String messagePayload) {
Log.info("message consumed: " + messagePayload);
}
}

How to get a Toast Notification when app running in foreground in wp8

I want to implement the "toast" notification inside my windows phone application. I'm implementing push message's, but I want them to show always. No matter if the application is running or not. The push notification will handle it when the application is closed, but not when it is running. Also if I create a shelltoast manually it won't show. To make it more difficult I can't use any external dll's. I only want to use code. What would be the best way to do this? I already know about the ToastNotificationRecieved event. I want to know how to implement it so that it will show a "toast" like message without using a framework
My code is below
PushPlugin.cs(c# code)
public void showToastNotification(string options)
{
ShellToast toast;
if (!TryDeserializeOptions(options, out toast))
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Deployment.Current.Dispatcher.BeginInvoke(toast.Show);
}
public void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
var toast = new PushNotification
{
Type = "toast"
};
foreach (var item in e.Collection)
{
toast.JsonContent.Add(item.Key, item.Value);
}
this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
}
In javascript
function onNotificationWP8(data) {
var pushNotification;
pushNotification = window.plugins.pushNotification;
pushNotification.showToastNotification(successHandler, errorHandler,
{
"Title": data.jsonContent["wp:Text1"], "Content": data.jsonContent["wp:Text2"], "NavigationUri": data.jsonContent["wp:Param"]
});
}
On devices without Windows Phone 8 Update 3, toast notifications are not displayed when the target app is running in the foreground. On devices with Windows Phone 8 Update 3, toast notifications are displayed when the target app is running in the foreground, but is obscured by other activity such as a phone call or the lock screen.
The following C# code example shows the properties used to create a toast notification using local code.
// Create a toast notification.
// The toast notification will not be shown if the foreground app is running.
ShellToast toast = new ShellToast();
toast.Title = "[title]";
toast.Content = "[content]";
toast.Show();
This thread has it all you looking for
public static class Notification
{
public static string ChannelURI = string.Empty;
public static void MainNotificationCallFunction()
{
try
{
NotificationMessage("Test Notification");
}
catch (Exception e)
{ }
}
public static void NotificationMessage(string Message)
{
try
{
ToastTemplateType toastType = ToastTemplateType.ToastText02;
XmlDocument toastXmlJob = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastTextElementJob = toastXmlJob.GetElementsByTagName("text");
toastTextElementJob[0].AppendChild(toastXmlJob.CreateTextNode(Message));
IXmlNode toastNodeJob = toastXmlJob.SelectSingleNode("/toast");
((XmlElement)toastNodeJob).SetAttribute("duration", "long");
ToastNotification toastJob = new ToastNotification(toastXmlJob);
ToastNotificationManager.CreateToastNotifier().Show(toastJob);
}
catch (Exception e)
{ }
}
public static void PushNotification()
{
try
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
string channelName = "Usman's Channel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
//// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
pushChannel.Open();
pushChannel.BindToShellTile();
pushChannel.BindToShellToast();
}
else
{
//// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
}
}
catch (Exception ex)
{ }
}
private static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
catch (Exception ex)
{ }
}
private static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
catch (Exception ex)
{ }
}
private static void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Notification {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)));
}
catch (Exception ex)
{ }
}
private static void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//ProgressBarPushNotifications.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show(e.ChannelUri.ToString(), "Uri Recieved", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message.AppendFormat(reader.ReadToEnd());
}
// Display a dialog of all the fields in the toast.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(message.ToString());
});
}
catch (Exception ex)
{ }
}
}

Future get() gets nullpointer exeception in java

I'm implementing a function that detects if there is a webcam. This piece of code works fine in windows and I had no problem with it in linux centos OS. Now I'm trying to run the same code in Ubuntu, here an exception is thrown.
Exception in thread "main" java.lang.NullPointerException
at CameraProperties.CheckForCameraPlugin.check(CheckForCameraPlugin.java:51)
at Main.Main.main(Main.java:39)
The code is given below.
public boolean check()
{
boolean b = true;
service = Executors.newFixedThreadPool(1);
task = service.submit(new InitialCameraChecker());
try
{
final String str;
// waits the 10 seconds for the Callable.call to finish.
str = task.get();
if (str.matches("nodevice"))
{
b = false;//Return false if no camera device found
}
else
{
b = true;
}
}
catch (InterruptedException | ExecutionException ex)
{
msgbox.showJoptionPane(15);
}
service.shutdownNow();
return b;
}
The callable class is given below
class InitialCameraChecker implements Callable<String>
{
private List<Integer> devices = new ArrayList<Integer>();
private final static String VERSION_ID = "1.0.0";
private String res;
//Checking for the Camera
public String call()
{
try
{
loadWebcam();
discoverDevices();
if (devices.isEmpty())
{
res = "nodevice";//No we cam device found
}
else
{
res = "founddevice";//Found Web Cam Device
}
}
catch (Exception ex)
{
System.out.println("Exception_logout" + ex.toString());
}
return res;
}
//Discovering the camera device
private void discoverDevices()
{
for (int i = 0; i < 10; i++)
{
CvCapture cap = null;
try
{
cap = cvCreateCameraCapture(i);
int res = cvGrabFrame(cap);
if (res > 0)
{
devices.add(i);
break;
}
}
catch (Exception e)
{
System.out.println("Exception in camaracheck Thread1");
}
finally
{
if (cap != null)
{
try
{
cvReleaseCapture(cap.pointerByReference());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
//Loading the dlls for starting the camera
private void loadWebcam()
{
String tmpDir = System.getProperty("java.io.tmpdir");
File faPath = new File(tmpDir + File.separator + "WebcamApplet_" + VERSION_ID.replaceAll("\\.", "-"));
System.setProperty("jna.library.path", faPath.getAbsolutePath());
}
}
Please tell me what is the problem. This works fine in windows.

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help

Http Post with Blackberry 6.0 issue

I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}