Azure Mobile Service calls hangs - xamarin.android

Using Xamarin.Forms app. When mobile data connection fluctuates on Android devices, e.g. network from 3G to 2G connection, or vice versa - the call seems to get hung somewhere.
This is the Azure API call :
public Task<ObservableCollection<Models.Item>> GetItemsByID(string tenantID, string auth_token)
{
return Task.Factory.StartNew(() =>
{
var res = RestClient.Get<ObservableCollection<Models.Item>>(HttpWebRequest.Create(string.Format(EndPointsList.GetItemsUrl + "tenantID={0}", tenantID)),auth_token);
return res ;
});
}
We initiate the System.Net.WebRequest here :
public static T Get<T>(WebRequest request, string auth_token, string requestData = null)
{
string result = string.Empty;
request.ContentType = "application/json";
request.Headers["ZUMO-API-VERSION"] = "2.0.0";
if (auth_token.StartsWith("Bearer"))
request.Headers["Authorization"] = auth_token;
else {
request.Headers["x-access_type"] = "offline";
request.Headers["x-zumo-auth"] = auth_token;
}
try
{
WebResponse webResponse = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).Result;
using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
var typ = typeof(T);
if (
typ == typeof(String)
|| typ == typeof(float)
|| typ == typeof(Decimal)
|| typ == typeof(Int16)
|| typ == typeof(Int32)
|| typ == typeof(Int64)
)
{
return (T)Convert.ChangeType(result, typeof(T), null);
}
return result.FromJson<T>();
}
catch (AggregateException agEx)
{
AggregateException(agEx);
return result.FromJson<T>();
}
catch (Exception ex)
{
return result.FromJson<T>();
}
}
This is the call from ViewModel
public async Task GetAllItems()
{
try
{
if (!this.IsInternetConnectionAvailable())
{
await this.CurrentContentPage.DisplayAlert("", AppResources.InternetConnectionNotAvailable, AppResources.Ok);
return;
}
this.ProgressBar.ShowProgress(AppResources.Loading);
ItemList = await this.ItemService.GetItemsByID(App.Locator.Login.LoggedInUser.TenantID.ToString(),Settings.AuthToken);
if (ItemList != null)
{
for (int i = 0; i < this.ItemList.Count; i++)
{
ItemList[i].RowColor = (i % 2 == 0 ? Theme.EvenRowColor : Theme.OddRowColor);
}
}
RaisePropertyChanged("ItemList");
}
catch (Exception ex)
{
ExceptionHandler.HandleException(CurrentContentPage, ex);
}
finally
{
this.ProgressBar.Dismiss();
}
}
In actual case here - the ProgressBar will kept on be displayed on the device, though its in Finally block. User have to kill the application to make it work again.
And we're unsuccessful to reproduce this back in lab. It only happens on field during intermittent connections.
Any abnormalities in the code? If not, how can we capture this in application log.

Related

No permanent connection to the port

I've got a device to my computer and I want to read its data from port 2005
I use the following code to read from the 2005 port.
public MainWindow()
{
try
{
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localAddr = IPAddress.Parse(ip.ToString());
}
}
TcpClient client = null;
try
{
client = new TcpClient(localAddr.ToString(), 2005);
}
catch (SocketException se)
{
}
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
DecodeReceivedMsg(data);
}
client.Close();
}
}
catch (SocketException e)
{
}
finally
{
}
}
My problem is that I do not always read the port, and many times, the while(true) does not run.
please guide me

Xamarin iOS Bluetooth Low Energy - CBPeripheral.UpdatedCharacteristicValue reading TX characteristic shows unexpected data

I recently received a BLE device for Bluetooth to Serial. It uses TruConnect and I'm trying to get it to communicate with my serial device. The serial device receives communication over a serial cable and echoes back anything that is sent to it as well as any results from a command that is sent.
Right now I'm simply trying to send TruConnect commands to the BLE device to check the current baud rate that the BLE device is set for.
I wrote some code based on this TruConnect guide that I found:
https://truconnect.ack.me/1.5/apps/communicating_via_ble#reading_from_a_truconnect_device_serial_interface.
The problem seems to be that whenever I try to read anything from the tx characteristic when there should be data, the data is not right.
Setting up CBPeripheral events:
private void setupPerif(CBPeripheral perf)
{
selectedPeripheral = perf;
selectedPeripheral.UpdatedCharacterteristicValue += (sender, e) =>
{
var c = e.Characteristic;
if (c != null)
{
var uuid = c.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
//
}
else if (uuid == UUID_TX)
{
// expecting bytes to contain valid response data
// it almost always contains twenty 0s.
byte[] bytes = c.Value.Where(i => i != 13).ToArray();
var invalidBytes = c.Value.Where(i => i > 127).ToArray();
var nonZeros = c.Value.Where(i => i != 0).ToArray();
if (nonZeros.Length < 1)
{
return;
}
else
{
foreach (byte b in bytes)
handler.handleByteReceived((char)b);
}
}
else if (uuid == UUID_MODE)
{
//
}
}
};
selectedPeripheral.DiscoveredService += (sender, e) =>
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService service in services)
{
if (service.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
truConnect = service;
selectedPeripheral.DiscoverCharacteristics(truConnect);
}
}
}
};
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to stream mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};
selectedPeripheral.WroteCharacteristicValue += (sender, e) =>
{
// if UUID is for RX, we just wrote to RX. Drill down to
// TX characteristic and read it. This will trigger
// the UpdatedCharacteristicValue event.
string uuid = e.Characteristic.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService s in services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
var charachteristics = s.Characteristics;
if (charachteristics != null && charachteristics.Length > 0)
{
foreach (CBCharacteristic c in charachteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_TX)
{
Timer t = new Timer(new TimerCallback(delegate(object o)
{
selectedPeripheral.ReadValue(c);
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(-1));
}
}
}
}
}
}
}
};
manager.ConnectPeripheral(selectedPeripheral);
}
Writes to rx. This is what should be used to actually send commands.
public void sendCommand(string command)
{
command += endString + "\n";
if (rx != null)
{
NSData d = NSData.FromString(command);
foreach (CBService s in selectedPeripheral.Services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
foreach (CBCharacteristic c in s.Characteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_RX)
selectedPeripheral.WriteValue(NSData.FromString(command), c, CBCharacteristicWriteType.WithResponse);
}
}
}
}
So my question is, why am I not getting the expected data when the CBPeripheral.UpdatedCharacteristicValue event is called? Occasionally I will get the expected data, but it is quite rare, and I can't seem to find any logical reason or pattern that would explain why this is happening.
AHA! I figured it out!
The problem was that I need to set the notify value for the appropriate characteristics. After doing that, I didn't need to call CBPeripheral.ReadValue(CBCharacteristic).
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
// set the notify value to true and poof!
// now CBPeripheral.UpdatedCharacteristicValue
// event will be triggered at the appropriate time.
selectedPeripheral.SetNotifyValue(true, tx);
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to remote command mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};

blackberry app not running on gprs connection in device

Hi am trying to run my app on blackberry device using Edge gprs connection but its not rendering the pages.i have tried lot to get the connection,also i tried the various links to solve, one of the simple code i have attached here, kindly guide me to solve this
public static String getConnectionString() {
String value="" ;
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
value=";interface=wifi";
}else{
value=";deviceside=true";
}
return value;
}
Append the connection string to your url. Then try
public static String getConnectionString() {
// This code is based on the connection code developed by Mike Nelson of
// AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceSide=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// System.out.println("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// System.out.println("Carrier coverage.---->>" + CoverageInfo.getCoverageStatus());
String carrierUid = getCarrierBIBSUid();
// DebugScreen.Log(" carrierUid is: " + carrierUid);
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// System.out.println("No Uid");
String wapString = getAvailableConnectionsString();
// DebugScreen.Log("from wap2 connection--->" + wapString);
if(wapString == null){
connectionString = ";deviceside=true";
}else{
connectionString = wapString;
}
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=true;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// System.out.println("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
// System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
Add this method and append connection String to url.
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for ippp--------->>" + records[currentRecord].getCid().toLowerCase());
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for bibs..........'''''" + records[currentRecord].getName().toLowerCase().indexOf("bibs") );
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public static String getAvailableConnectionsString() {
String conns = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
String cid;
String uid;
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
// System.out.println("record name:"+myRecord.getName()+" cid:"+myRecord.getCid().toLowerCase()+" "+myRecord.getUid().toLowerCase());
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
//Wap2.0
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1 ) {
conns = ";deviceside=true" + ";ConnectionUID="+ myRecord.getUid();
if(myRecord.getUid().equalsIgnoreCase("GTCP BIBS")){
return conns;
}
}
}
}
return conns;
}
This code is work for me..

HttpConnection connect with Mobile Network or 3G

When I run this application on a device using the WiFi
it's working fine. But when I am using a mobile network or 3g it's giving an error.
It's not working on the mobile network.
I am using this code:
connection = (HttpConnection) Connector.open(APIURL+ updateConnectionSuffix());
And my ConnectionTools class code:
public String updateConnectionSuffix() {
String connSuffix;
if (DeviceInfo.isSimulator()) {
connSuffix = ";deviceside=true";
} else if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
connSuffix = ";interface=wifi";
} else {
String uid = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null
&& records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1)
&& (records[i].getUid().toLowerCase().indexOf(
"wifi") == -1)
&& (records[i].getUid().toLowerCase().indexOf(
"mms") == -1)) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null) {
// WAP2 Connection
connSuffix = ";ConnectionUID=" + uid;
} else {
connSuffix = ";deviceside=true";
}
}
return connSuffix;
}
Can you give me any solutions?
What should we do for the mobile network or 3g?
Try this code.
public static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Replace this function by your updateConnectionSuffix().
Let me explain : - This is for connection using mobile network 2g or 3g any network" just copy & paste & enjoy
String url = "vm.b24esolution.com:9090";
final HttpConnection connection = (HttpConnection) Connector.open("socket://"+url+updateConnectionSuffix()+";apn=rim.net.gprs;tunnelauthusername =;tunnelauthpassword=",Connector.READ_WRITE);

Check wifi condition in Blackberry application

I have developed an application for blackberry devices. The application is working fine if it uses internet via data service provider.
I have BB 9550 and I want to use my application using wifi. I tried a lot but I cant get proper answer to check wifi condition.
How we can differentiate to run our application for wifi or data service provider?
For checking wifi is connected or not the following method will help you.
public static boolean isWifiConnected()
{
try
{
if (RadioInfo.getSignalLevel(RadioInfo.WAF_WLAN) != RadioInfo.LEVEL_NO_COVERAGE)
{
return true;
}
}
catch(Exception e)
{
System.out.println("Exception during get WiFi status");
}
return false;
}
if wifi is not connected the following methods will help to add data service.
public static String getConnParam(){
String connectionParameters = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// Connected to a WiFi access point
connectionParameters = ";interface=wifi";
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
ServiceRecord record = getWAP2ServiceRecord();
if (record != null
&& (coverageStatus & CoverageInfo.COVERAGE_DIRECT) ==
CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
connectionParameters = ";deviceside=true;ConnectionUID="
+ record.getUid();
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) ==
CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connectionParameters = ";deviceside=false";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) ==
CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage but no WAP 2.0 service book record
connectionParameters = ";deviceside=true";
}
}
return connectionParameters;
}
private static ServiceRecord getWAP2ServiceRecord() {
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
for(int i = 0; i < records.length; i++) {
String cid = records[i].getCid().toLowerCase();
String uid = records[i].getUid().toLowerCase();
if (cid.indexOf("wptcp") != -1 &&
uid.indexOf("wifi") == -1 &&
uid.indexOf("mms") == -1) {
return records[i];
}
}
return null;
}
Example to use above methods.
String connParams=(isWifiConnected())?";interface=wifi":getConnParam();
Hope This will help you
try this:
private static String getParameters() {
if (GetWiFiCoverageStatus()) {
return ";deviceside=true;interface=wifi";
}
else {
return yourParametersForEdge
}
}
private static boolean GetWiFiCoverageStatus() {
if((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)) {
return true;
}
else
return false;
}
And when you need to connect, you'll have to add the parameters to the URL:
yourUrl = yourUrl + getParameters();

Resources