Javamail : Proper way to issue idle() for IMAPFolder - jakarta-mail

I have set MessageCountListener for IMAPFolder. In order to get updates continuously I had to do the following, which is a killer for my app performance wise. It freezes the GUI since it's running for each and every folder.
while (true) {
try {
if (folder != null && folder.isOpen()) {
folder.idle();
} else {
getSyncListenersAttachedFolders().remove(syncFolder.getFolderID());
}
} catch (Exception ex) {
errorLOG.error("IDLE command issue exception.");
getSyncListenersAttachedFolders().remove(syncFolder.getFolderID());
}
}
Is there any better way of issuing idle command which will not run in a while(true) condition.
Expecting a quick response. Thanks in advance.

You need to run it in its own thread.

Related

System.Windows.Clipboard and MS Office applications

I am currently using System.Windows.Clipboard to: set some text, call SendInput with control+V, finally restoring the previous clipboard.
This works in most applications, though in Microsoft's Office applications the send input is causing the previous clipboard to be restored. I am assuming it is something to do with a delay in the SendInput method, so I added a wait before restoring and resolved the issue for most users, but Outlook for a user is still restoring the previous clipboard.
is there a better way of doing it than below?
try
{
//method that uses GetDataObject and stores it to be restored
_clipboard.Acquire();
try
{
_clipboard.SetText(ClipboardText);
//a wrapper for SendInput()
SendInputWrapper.SendKeyCombination(new KeyCode(VirtualKeyShort.Control),
new KeyCode(VirtualKeyShort.KeyV));
}
finally
{
//without this pause word and outlook would paste the original clipboard
await Task.Delay(TimeSpan.FromMilliseconds(200));
//wrapper method for Clipboard.SetDataObject() using the above stored
clipboard
_clipboard.Restore();
}
}
catch (Exception ex)
{
_log.Error("Error caught pasting text", ex);
}
Though it does not answer my direct question to Offices Clipboard buffer, the solution I have which now works is using Word.Interop:
var currentSelection = _word.Selection;
// Store the user's current Overtype selection
var userOvertype = _word.Options.Overtype;
// Make sure Overtype is turned off.
if (_word.Options.Overtype) _word.Options.Overtype = false;
// Test to see if selection is an insertion point.
if (currentSelection.Type == WdSelectionType.wdSelectionIP)
currentSelection.TypeText(text);
else if (currentSelection.Type == WdSelectionType.wdSelectionNormal)
{
// Move to start of selection.
if (_word.Options.ReplaceSelection)
{
object direction = WdCollapseDirection.wdCollapseStart;
currentSelection.Collapse(ref direction);
}
currentSelection.TypeText(text);
}
// Restore the user's Overtype selection
_word.Options.Overtype = userOvertype;

Apache Flink JobListener does not work expected

I wrote a flink batch job in flink 1.11.1. After job finishes successfull y, I want to do something like calling a http service.
I added a simple job listener to hook job status. The problem is when when kafka sink operator throws a error, job listener does not triggered. I expect when my job failed, it should trigger my job listener and print fail log.
How can I be sure that the job is done successfully or not?
Any help will be appreciated.
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.registerJobListener(new JobListener {
override def onJobSubmitted(jobClient: JobClient, throwable: Throwable): Unit = {
if (throwable == null) {
log.info("SUCCESS")
} else {
log.info("FAIL")
}
}
override def onJobExecuted(jobExecutionResult: JobExecutionResult, throwable: Throwable): Unit = {
if (throwable == null) {
log.info("SUCCESS")
} else {
log.info("FAIL")
}
}
})
env.createInput(input)
.filter(r => Option(r.token).getOrElse("").nonEmpty)
.addSink(kafkaProducer)
If you try to run the job on cluster, you can view your logger message and stdout in the console with your job id. Please refer the attached screenshot,
The default url could be http://localhost:8081 if your run on local cluster.
Again, the below is not correct approach to check your job is success or not.
if (throwable == null) {
log.info("SUCCESS")
} else {
log.info("FAIL")
}

How to kill intent Service

I am using wakefull intent service and works very fine. But currently i see that many times my intent service is in wait satate.I found that problem is with javamail as it goes in deadlock state when ever internet connection is resets.
I search option to intrupt operation java mail but can't find any solution.I have set IMAP,SMTP Time out property but it is not working.
if(msg1[0]!= null)
{
if(!Mail.store.isConnected() || f== null)
{
Log.v(tag, "StoreNot Connected");
m = new Mail(username, password);
f =m.getlable("Message_"+nick);
Log.v(tag, "Store Connected");
}
try{
Log.v(tag, "Sending Mail");
//Get DeadLock Hear
f.appendMessages(msg1);
sucess_flag=1;
Log.v(tag, "Mail Send");
}
catch(Exception e)
{
e.printStackTrace();
}catch(Throwable e)
{
e.printStackTrace();
}
}
So now i am looking for an option to restart or kill the current intent service.
Is there any option for this?
If not then is it a good idea to create theads from intentservice and kill them instead?
Try this:
Intent GPSService = new Intent(context, TrackGPS.class);
context.stopService(GPSService);

invalid cross-thread access in release

I have a lightswitch application needs to generate Crystal Report from it's WCF Ria. In the development runtime I am able to generate correctly without errors, but when I push it to release environment it prompt error - invalid cross-thread access.
I've read some articles already and it is very likely Silverlight UI Thread problem
partial void GenerateReport_Execute()
{
try
{
GenerateCrystalReport.Load();
var temp = DataWorkspace.QUMCrystalReportDomainData.GenerateCrystalReport(SearchQuery.SelectedItem.GroupId, sQuarter, sYear, eQuarter, eYear);
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
var uri = new Uri("C:\\Temp\\ReportTest.pdf", UriKind.RelativeOrAbsolute);
if (AutomationFactory.IsAvailable)
{
var shell = AutomationFactory.CreateObject("Shell.Application");
shell.ShellExecute(uri.ToString());
}
else if (!System.Windows.Application.Current.IsRunningOutOfBrowser)
{
HtmlPage.Window.Navigate(uri, "_blank");
}
else
{
throw new InvalidOperationException();
}
});
}
catch ( Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Am I doing incorrectly? please help me identify this.
Thanks in Advance
Sam
Answering my question, basically that messagebox at bottom is causing the UI problem.
Lightswitch's dispatcher is not same as wpf's dispatcher(what that messagebox uses), please correct if I'm wrong

WP7 check if internet is available

My app WP7 was not accepted because it fails to load if the internet is not available. I looked for a way to check it and found this command
NetworkInterface.GetIsNetworkAvailable()
But it isn't working on the emulator and I do not have any device to test it.
Could someone tell me if it returns false if the device is in Airplane mode? If not, how can I check for it?
Thanks,
Oscar
Edit: I also tried with this code:
try
{
wsClient.CurrenciesCompleted += new EventHandler<CurrencyConversion.CurrenciesCompletedEventArgs>(wsClient_CurrenciesCompleted);
wsClient.CurrenciesAsync(null);
}
catch
{
NetworkNotAvailable();
}
But I am not able to catch the exception, I also tried in the wsClient_CurrenciesCompleted method, but also no good.
Where could I test it?
Don't test for "the internet in general" - test for the service you'll actually be connecting to. Test for it by trying to connect to it - make some simple, non-destructive request on start-up. Yes, that will take a tiny bit of the user's data allowance, but:
You will be warming up the networking stack and making a connection which should end up being kept alive automatically, so future latency will be reduced.
You could warn the user that they may have limited functionality if the connection fails.
An Alternative to Jon's suggestion is to check which network interface is available. This is very handy in cases were you need to adjust which service you call based on network speed. For example the switch statement below could be modified to return an Enum to represent the quality of the network.
public class NetworkMonitorClass
{
private Timer timer;
private NetworkInterfaceType _currNetType = null;
private volatile bool _valueRetrieved = false;
public NetworkMonitorClass()
{
//using a timer to poll the network type.
timer = new Timer(new TimerCallBack((o)=>
{
//Copied comment from Microsoft Example:
// Checking the network type is not instantaneous
// so it is advised to always do it on a background thread.
_currNetType = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
_valueRetrieved = true;
}), null, 200, 3000); // update the network type every 3 seconds.
}
public NetworkInterfaceType CurrentNetworkType
{
get
{
if(false == _valueRetrieved ) return NetworkInterfaceType.Unknown;
return _currNetType;
}
private set { ;}
}
public bool isNetworkReady()
{
if(false == _valueRetrieved ) return false;
switch (_currentNetworkType)
{
//Low speed networks
case NetworkInterfaceType.MobileBroadbandCdma:
case NetworkInterfaceType.MobileBroadbandGsm:
return true;
//High speed networks
case NetworkInterfaceType.Wireless80211:
case NetworkInterfaceType.Ethernet:
return true;
//No Network
case NetworkInterfaceType.None:
default:
return false;
}
}
}
See http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.networkinterface.networkinterfacetype(VS.92).aspx
GetIsNetworkAvailable() will always return true in the emulator. For testing in the emulator you'll need to work round this in code.
This can be a useful quick check but you also (as Jon pointed out) need to handle the scenario of not being able to connect to your specific server.
Handling this can be done by catching the WebException when you try and get the response in the callback.
private static void DownloadInfoCallback(IAsyncResult asynchronousResult)
{
try
{
var webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// This will cause an error if the request failed
var webResponse = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
.....
}
catch (WebException exc)
{
// Handle error here
}
}
GetIsNetworkAvailable() works properly on device.
You can mock your handling of this for testing in the emulator using Microsoft.Devices.Environment.DeviceType.
I would be inclined to test both for avaiability of the internet and availability of your site through exception handling and provide feedback to the user of the app that indicates what the true reason is for features being unavailable.

Resources