I'd like to know if there is a way to check if a User have Private Messages Enabled.
This Feature is for an Support Bot. Currently I use the GuildMessageRecievedEvent and send a Private Message to the User.
No, there is not. You can only send a message and handle the failure:
user.openPrivateChannel().submit()
.thenCompose(channel -> channel.sendMessage(x).submit())
.whenComplete((message, error) -> {
if (error != null) failed();
else success();
});
Related
My app tries to do an async network request at app launch, using RequestBuilder request = Rest.get, as described in this article: https://www.codenameone.com/blog/rest-api-error-handling.html. If I power off my testing server, at the app launch I have this exception:
[Network Thread] 0:0:0,586 - Exception: java.net.ConnectException - Connection refused
but no info, message or dialog is shown to the user. The following boilerplate code in the init() is not called:
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if (err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
If I provide a custom network error handler, with request.onError(networkError);, the issue is the same: my network error handler is not called. I tried to implement it so (it's very similar to the above boilerplate code):
private static final ActionListener<NetworkEvent> networkError = new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent err) {
Log.p("NETWORK ERROR connecting to the server");
err.consume();
if (err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
DialogUtilities.genericNetworkError();
}
};
I tried using the Simulator with the server offline. Then I tried with Android and iOS app, disconnecting the device from the Internet, but also in this case there is no message to the user. What's wrong?
Note that the error code handlers used with onErrorCodeBytes, onErrorCodeJSON and onErrorCodeString seem to work correctly (they are invoked, for example, if I have a 404 http code).
Did you define onError?
It should be invoked for exceptions and might override the global error handling logic once defined.
I tried this case with wifi turned off and it seems to have worked correctly:
Button test = new Button("Test");
test.addActionListener(e -> {
Rest.get("https://www.codenameone.com/").
onError(ee -> {
if(ee.getError() != null) {
Log.e(ee.getError());
}
}).
fetchAsBytes(call -> {});
});
codenameone: how to handle exception java.net.ConnectionException explicitly
I want to handle exception explicitly.Currently when I am handling exception It handled implicitly first in which shows the exception message on screen in detail.I don't want to show in detail error message on screen(pop up dialog).
right now it shows the exception Java.net.Connection Exception: Connection refused for URL http:localhost/login connection refused.instead of this message i just want to show "connection refused" message on pop-up dialog
Can you please let me know how to resolve it.
On mobile devices the error might be quite different to the one on the simulator since we are dealing with native API's under the surface. See the error handling section of the networking section in the developer guide:
There are two distinct placed where you can handle a networking error:
The ConnectionRequest - by overriding callback methods
The NetworkManager error handler
Notice that the NetworkManager error handler takes precedence thus allowing you to define a global policy for network error handling by consuming errors.
E.g. if I would like to block all network errors from showing anything to the user I could do something like this:
NetworkManager.getInstance().addToQueue(request);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
The error listener is invoked first with the NetworkEvent matching the error. Consuming the event prevents it from propagating further down the chain into the ConnectionRequest callbacks.
We can also override the error callbacks of the various types in the request e.g. in the case of a server error code we can do:
ConnectionRequest request = new ConnectionRequest(url, false) {
protected void handleErrorResponseCode(int code, String message) {
if(code == 444) {
// do something
}
}
protected void handleException(Exception err) {
// handle exception that occurred. Notice you can either have this or have the listener on the NetworkManager
}
protected void readResponse(InputStream input) {
// just read from the response input stream
}
};
NetworkManager.getInstance().addToQueue(request);
I'm testing the behavior of the .net LDAP client when a bad password is provided enough times to trigger a lockout.
I see this odd behavior: it seems that if the process successfully connected at any time, then it is able to re-connect even after purposefully triggering a lockout.
Here's a shorthand version of my binding method:
private DirectoryEntry Bind(string userId, string password)
{
var entry = new DirectoryEntry(BasePath, userId, password);
// If the password is bad, the attempt to access entry.NativeObject throws an exception.
var obj = entry.NativeObject; // causes the bind to occur
return entry;
}
My test proceeds as follows:
private void TestLockout()
{
// attempt with bad pw enough times to trigger a lockout.
for (int i=0; i < 5; i++)
{
try
{
// i.ToString() is a purposefully bad pw
Bind("testuser", i.ToString());
}
catch
{
}
}
// Now make sure that an attempt with a good pw fails due to lockout
var bindSuccess = true;
try
{
Bind("testuser", "correctpassword");
}
catch
{
bindSuccess = false;
}
// the output should be "false"
Console.WriteLine("Bind result is " + bindSuccess.ToString();
}
This works fine as is. However, if a call to Bind() with a good password precedes the test, I get different results.
IOW, this:
Bind("testuser", "correctpassword"); // succeeds
TestLockout(); // does not give the correct result
The following happens.
a) TestLockout produces incorrect output, because the final Bind succeeds and it should not.
b) Yet, I know that the user was locked out, because of subsequent inspection.
So it appears that some component is tracking whether the current process ever connected successfully. I need to have a way to clear this condition. This authentication code will be executing in a long-running service process and it is not acceptable to authenticate a user when they are really locked out.
This is related to the fact that DirectoryEntry is using ADSI. ADSI has internal LDAP connection pool built based on the BasePath, Username and Password.
If you tried to bind with the correct password before the account was locked out, an LDAP connection was successfully made using that correct password and cached in the connection pool. Then, you made your account locked out and tried to bind to the Active Directory using the same BasePath, Username and Password. DirectoryEntry at this time will not establish a new LDAP connection but reuse the previous one. You can prove that by looking at the network trace.
To fix it, you can dispose your DirectoryEntry when you don't need it. Once your DirectoryEntry is disposed, ADSI should be smart enough to close the LDAP connection that it no longer requires. In your sample code, it looks like you never need it again. So, this should fix the problem.
private void Bind(string userId, string password)
{
using (var entry = new DirectoryEntry(BasePath, userId, password))
{
// If the password is bad, the attempt to access entry.NativeObject throws an exception.
var obj = entry.NativeObject; // causes the bind to occur
}
}
CaptureDeviceConfiguration.RequestDeviceAccess() method must be invoked by user interaction, otherwise it fails. My question is how does Silverlight know the invocation came from user (i.e. via Button.Click())?
Have a look at this: http://liviutrifoi.wordpress.com/2011/05/18/silverlight-isolatedstoragefile-increasequotato/
Quote:
I was curios though how exactly does silverlight know what a user
initiated event is, but after digging through .net framework source
code I’ve got to a dead end:
if ((browserService == null) || !browserService.InPrivateMode())
{
//..
}
return false; //means that IncreaseQuota will fail
where browser.IsInPrivateMode is:
[SecuritySafeCritical]
public bool InPrivateMode()
{
bool privateMode = false;
return (NativeMethods.SUCCEEDED(UnsafeNativeMethods.DOM_InPrivateMode(this._browserServiceHandle, out privateMode)) && privateMode);
}
where DOM_InPrivateMode is in a DllImport["agcore"], which according
to microsoft is confidential :( So it looks like I won’t find out soon
how they’re detecting user initiated events, although I’m guessing
they have some centralized private method that detects clicks for
example, and then probably sets a flag that this was indeed “a user
initiated event”, and since you can’t forge clicks or keypresses using
javascript and since you can’t call those private methods using
reflection, it’s “safe”.
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.