I would like to check if mobile data is available (the app has access, it's switched on in settings, aeroplane mode isn't on and there is a valid connection).
I want to know this even when an active wifi connection is established. So I can't use any get the current connection as it won't be the current one, WiFi would be.
I have tried looking into NWPath and NWPathMonitor but got a bit confused by it all.
Thanks, if I need to add any more information just drop a comment and I will update this or reply to you.
Since you have a Tag with Xamarin, just use the API from Essentials. For the connectivity-checker see the docs.
Here is a pretty perfekt blogpost from "James Montemagno"
A sneak preview of the Post:
var current = Connectivity.NetworkAccess;
switch(current)
{
case NetworkAccess.Internet:
// Connected to internet
break;
case NetworkAccess.Local:
// Only local network access
break;
case NetworkAccess.ConstrainedInternet:
// Connected, but limited internet access such as behind a network login page
break;
case NetworkAccess.None:
// No internet available
break;
case NetworkAccess.Unknown:
// Internet access is unknown
break;
}
Edit due to the comment from #Samuel James:
Maybe this helps?
Check what type of activ connection (according docs from Mircosoft):
var profiles = Connectivity.ConnectionProfiles;
if (profiles.Contains(ConnectionProfile.Cellular))
{
// Active mobile/cellular data connection.
}
public enum ConnectionProfile
{
/// <summary>Other unknown type of connection.</summary>
Unknown,
/// <summary>The bluetooth data connection.</summary>
Bluetooth,
/// <summary>The mobile/cellular data connection.</summary>
Cellular,
/// <summary>The ethernet data connection.</summary>
Ethernet,
/// <summary>The WiFi data connection.</summary>
WiFi
}
See my answer here ,we can use CoreTelephony framework to get what the specific type of cellular is .
Try the following code
public ConnectivityTest()
{
// Register for connectivity changes, be sure to unsubscribe when finished
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
}
string result;
void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
var access = e.NetworkAccess;
var profiles = e.ConnectionProfiles;
if (Connectivity.NetworkAccess != NetworkAccess.Internet)
{
result = "NoNetworkAccess";
}
else if (profiles.Contains(ConnectionProfile.Cellular))
{
CTTelephonyNetworkInfo networkInfo = new CTTelephonyNetworkInfo();
string carrierTypeName = networkInfo.ServiceCurrentRadioAccessTechnology.Values[0];
if (carrierTypeName == null) result = "unknown";
else if (carrierTypeName == CTRadioAccessTechnology.GPRS ||
carrierTypeName == CTRadioAccessTechnology.Edge ||
carrierTypeName == CTRadioAccessTechnology.CDMA1x)
result = "2G";
else if (carrierTypeName == CTRadioAccessTechnology.WCDMA ||
carrierTypeName == CTRadioAccessTechnology.HSDPA ||
carrierTypeName == CTRadioAccessTechnology.HSUPA ||
carrierTypeName == CTRadioAccessTechnology.CDMAEVDORev0 ||
carrierTypeName == CTRadioAccessTechnology.CDMAEVDORevA ||
carrierTypeName == CTRadioAccessTechnology.CDMAEVDORevB ||
carrierTypeName == CTRadioAccessTechnology.EHRPD)
result = "3G";
else if (carrierTypeName == CTRadioAccessTechnology.LTE)
result = "4G";
else result = "5G";
}
}
Refer to
https://stackoverflow.com/a/61327753/8187800
Related
I´m a technical project manager coordinating developers. My coding skills are limited and so I align with my devs on logical structure. For a mobile app (React Native to serve Android and iOS) we are currently developing user current location logic. Turned out we have specific Android and iOS settings, what may require native developmetn for location service handling.
I´m currently reviewing the following pseudocode and, besides others, concerned about the MULTIPLE IF statements and thinking if there is a more efficient way, as here we seem to jump into every IF, even when location is set already before.
I think there can be something like "until", "break" or similar .. and maybe relevant to consider the specific dev language, React Native in that case?
Any help, as pseudocode or if possible to make it specific already considering React Native, is very much appreciated.
Many thanks in advance!
Code
////Central Location Service to get current location.
var currentLocation;
var locationType
if Android {
DEFINED_ACCURACY = QUALITY_BALANCED_POWER
} else id iOS {
DEFINED_ACCURACY = kCLLocationAccuracyHundredMeters
}
DEFINED_DISTANCE = 3000
function startLocationService(){
var locationservice = LocationService()
locationservcie.accuracy = DEFINED_ACCURACY
locationservcie.distance = DEFINED_DISTANCE
locationservcie.startListnertoLocationUpdate() {
cacheData(location, currentTime);
currentLocation = location
}
}
function getLocationFromLocationService() {
if locationServcieEnabled == false
return NULL;
if locationPermissionGranted == false
return NULL;
return currentLocation;
}
function getCurrentLocation() {
var lcoation = NULL;
var accuracy = Not_defined;
lcoation = getLocationFromLocationService() //GPS, network
locationType = locationService
if lcoation == NULL {
locationdata == getLastKnownLocation()
if locationdata.Age < DEFINED_DURATION {
location = locationdata.location
locationType = locationService
}
}
if location == NULL {
location == getCachedLocationWithin24Hour()
locationType = locationService
}
if location == NULL {
location = getLocationfromTelephony()
locationType = other
}
if location == NULL {
if permissionToUseBilling == false {
askForPermissionToUseBilling()
}
location = getLocationFromBillimg()
accuracy = other
}
if location == NULL {
location = getLocationOfDEfaultCountry()
accuracy = other
}
return location, Other
}
I think you can use switches to cover different cases from javascript.
Probably your dev team knows, but did not want to bring it into pseudo code?
const location = getLocationFromLocationService() ;
switch (location) {
case 'NULL':
//DO SOMETHING WHEN NULL;
break;
case 'New York':
// DO SOMETHING WHEN New York;
// No break leads to run also into the next case
case 'Bern':
console.log('I love nice cities.');
break;
default:
console.log(`Sorry, we are out of ${location}.`);
}
Interestingly you seem to have multiple times the same if case?
Maybe you will to nest it or have to use a switch with multiple expressions.
case ("Bern" && "ANOTHERExpression to be true"):
Link to switch documentation
Please don't underestimate your dev team. ;-)
We have tried the approach suggested at:
https://msdn.microsoft.com/en-us/library/windows/hardware/dn312121(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/windows/hardware/dn303343(v=vs.85).aspx
We are able to find out list of all the magneticDevices using below code snippet
var magneticDevices = await DeviceInformation.FindAllAsync(aqsFilter);
but we are not able to get HidDevice object from the below code. It is giving null.
HidDevice device = await HidDevice.FromIdAsync(magneticDevices[0].Id
We have also set device capabilities in the app manifest file like below.
<DeviceCapability Name="humaninterfacedevice">
<Device Id="vidpid:0ACD 0520">
<Function Type="usage:0001 0006"/>
</Device>
</DeviceCapability>
<DeviceCapability Name="usb">
<Device Id="vidpid:0ACD 0520">
<Function Type="winUsbId:4d1e55b2-f16f-11cf-88cb-001111000030"/>
</Device>
</DeviceCapability>
Code for the complete Function
private async Task<bool> HasCardReader()
{
bool hasCardReader = false;
ushort usagePage = 0x0001;
ushort usageId = 0x0006;
ushort vendorId = 0x0ACD;
ushort productId = 0x0520;
var aqsFilter = HidDevice.GetDeviceSelector(usagePage, usageId, vendorId, productId);
var magneticDevices = await DeviceInformation.FindAllAsync(aqsFilter);
try
{
if (magneticDevices != null && magneticDevices.Count > 0)
{
HidDevice device = await HidDevice.FromIdAsync(magneticDevices[0].Id, Windows.Storage.FileAccessMode.Read);
inputReportEventHandler = new TypedEventHandler<HidDevice, HidInputReportReceivedEventArgs>(this.OnInputReportEvent);
device.InputReportReceived += inputReportEventHandler;
var watcher = DeviceInformation.CreateWatcher(aqsFilter);
watcher.Added += WatcherAdded;
watcher.Removed += WatcherRemoved;
watcher.Start();
hasCardReader = true;
}
else
{
}
}
catch (Exception ex)
{
Logging.LoggingSessionScenario.LogMessageAsync(ex.Message, LoggingLevel.Error);
}
return hasCardReader;
}
There are several reasons for the null return value, but I don't think there is something wrong with your code, since you can find the device by calling FindAllAsync. I will suggest you to troubleshoot this issue using this official HIDDevice sample on GitHub.
I successfully connected to my external hid device with that sample by changing the vid & pid & usagepage & usageid to my device.
In EventHandlerForDevice.cs, find the function OpenDeviceAsync, and you will notice the following possible reasons when null is returned by FromIdAsync.
else
{
successfullyOpenedDevice = false;
notificationStatus = NotifyType.ErrorMessage;
var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus;
if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
{
notificationMessage = "Access to the device was blocked by the user : " + deviceInfo.Id;
}
else if (deviceAccessStatus == DeviceAccessStatus.DeniedBySystem)
{
// This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
// This status does not cover the case where the device is already opened by another app.
notificationMessage = "Access to the device was blocked by the system : " + deviceInfo.Id;
}
else
{
// Most likely the device is opened by another app, but cannot be sure
notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id;
}
}
Have a try with that sample(Scenario1) and change the ids in both appxmanifest and SampleConfiguration.cs(class Device). If you cannot see your device in the device list, that means the configuration is incorrect for your device.
it is very first time i'm messing with sockets , and read many quotes that this is not for newbies.
so problem is i'm using php smpp library for sending SMS which works fine but after delivering two to three SMS delivery fails with following warning
Warning: stream_socket_sendto() [function.stream-socket-sendto]: An existing connection was forcibly closed by the remote host', and to make it work again i need to restart` apache.
Following is write function which throwing exception
public function write($buf) {
$null = null;
$write = array($this->handle_);
// keep writing until all the data has been written
while (strlen($buf) > 0) {
// wait for stream to become available for writing
$writable = #stream_select($null, $write, $null, $this->sendTimeoutSec_, $this->sendTimeoutUsec_);
if ($writable > 0) {
// write buffer to stream
$written = stream_socket_sendto($this->handle_, $buf);
if ($written === -1 || $written === false) {
throw new TTransportException('TSocket: Could not write '.$written.' bytes '.
$this->host_.':'.$this->port_);
}
// determine how much of the buffer is left to write
$buf = substr($buf, $written);
} else if ($writable === 0) {
throw new TTransportException('TSocket: timed out writing '.strlen($buf).' bytes from '.
$this->host_.':'.$this->port_);
} else {
throw new TTransportException('TSocket: Could not write '.strlen($buf).' bytes '.
$this->host_.':'.$this->port_);
}
}
}
Please anyone can put some light
It was the bug which i won't able to identify/ rectify. then i used an other library from http://www.codeforge.com/read/171085/smpp.php__html and it really saved me.
I want to implement an IQHandler, but I want to make sure that only authenticated users can send IQ Packets to it. I want to make sure that the JID I get from Packet.getFrom() is the authenticated user that sent it.
I need this so that no one can just create an IQ Packet and set the "from" attribute to a user id other than their own. Can someone help me with this?
Try this:
ClientSession session = sessionManager.getSession(sender);
if(session.getStatus() == Session.STATUS_AUTHENTICATED) {
//YOUR STUFF HERE
}
UPDATE:
Looking closer at the source. It appears that the IQRouter already does this for you. If you are not authenticated the server response with an error stating just that.
public void route(IQ packet) {
if (packet == null) {
throw new NullPointerException();
}
JID sender = packet.getFrom();
ClientSession session = sessionManager.getSession(sender);
try {
// Invoke the interceptors before we process the read packet
InterceptorManager.getInstance().invokeInterceptors(packet, session, true, false);
JID to = packet.getTo();
if (session != null && to != null && session.getStatus() == Session.STATUS_CONNECTED &&
!serverName.equals(to.toString())) {
// User is requesting this server to authenticate for another server. Return
// a bad-request error
IQ reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.bad_request);
session.process(reply);
Log.warn("User tried to authenticate with this server using an unknown receipient: " +
packet.toXML());
}
else if (session == null || session.getStatus() == Session.STATUS_AUTHENTICATED || (
isLocalServer(to) && (
"jabber:iq:auth".equals(packet.getChildElement().getNamespaceURI()) ||
"jabber:iq:register"
.equals(packet.getChildElement().getNamespaceURI()) ||
"urn:ietf:params:xml:ns:xmpp-bind"
.equals(packet.getChildElement().getNamespaceURI())))) {
handle(packet);
}
else {
IQ reply = IQ.createResultIQ(packet);
reply.setChildElement(packet.getChildElement().createCopy());
reply.setError(PacketError.Condition.not_authorized);
session.process(reply);
}
// Invoke the interceptors after we have processed the read packet
InterceptorManager.getInstance().invokeInterceptors(packet, session, true, true);
}
I want to call a Security Token Service which was created and deployed using Metro 2.2 framework from an Axis 2 STS Client. I'm trying to do the same but getting issues like the one below: -
java.lang.RuntimeException:Incorrect inclusion value: -1
I went deep into the source code and saw that in SecureConversationTokenBuilder class code is wriiten something like this:-
String inclusionValue = attribute.getAttributeValue().trim();
conversationToken.setInclusion(SP11Constants.getInclusionFromAttributeValue(inclusionValue));
then I went into the SP11Constants.getInclusionFromAttributeValue(inclusionValue) and saw the following piece of code:-
public static int getInclusionFromAttributeValue(String value ) {
if (INCLUDE_ALWAYS.equals(value)) {
return SPConstants.INCLUDE_TOEKN_ALWAYS;
} else if (INCLUDE_ALWAYS_TO_RECIPIENT.equals(value)) {
return SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT;
} else if (INCLUDE_NEVER.equals(value)) {
return SPConstants.INCLUDE_TOKEN_NEVER;
} else if (INCLUDE_ONCE.equals(value)) {
return SPConstants.INCLUDE_TOKEN_ONCE;
} else {
return -1;
}
}
as INCLUDE_ALWAYS = "http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always" which is not equal to what is defined by metro in policy.xml like
http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Always
Therefore the above code always return -1 and in turn throws a runtime exception as below:-
public void setInclusion(int inclusion) {
if(SPConstants.INCLUDE_TOEKN_ALWAYS == inclusion ||
SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == inclusion ||
SPConstants.INCLUDE_TOEKN_ALWAYS_TO_INITIATOR == inclusion ||
SPConstants.INCLUDE_TOKEN_NEVER == inclusion ||
SPConstants.INCLUDE_TOKEN_ONCE == inclusion ) {
this.inclusion = inclusion;
} else {
//TODO replace this with a proper (WSSPolicyException) exception
throw new RuntimeException("Incorrect inclusion value: " + inclusion);
}
}
Just wanted to know whether it is possible to get token from Security Token Service (STS) created in Metro Framework invoked from an Axis2 based STS Client.Please advise as I'm stuck in between.
Thanks in advance.