Internet lost connection Webbrowser - windows-phone-7

I have webrowser in app. I need to do something with webrowser when the internet connection is lost e.g. display MessageBox and when internet is again available reconnect to website. I find that can i use DeviceNetworkInformation.NetworkAvailabilityChanged Event, but when I 'm testing, the event is not firing.
I tried use DeviceNetworkInformation.IsNetworkAvailable, when navigating but this not have functionality that i want. I have testing in Nokia Lumia 710.
Here my simple code, i make him from example from msdn
http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.devicenetworkinformation.networkavailabilitychanged%28v=vs.92%29.aspx
DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler(NetworkAvailabilityChanged);
void NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
{
string info = string.Empty;
bool connection = false;
bool disco = false;
switch (e.NotificationType)
{
case NetworkNotificationType.InterfaceConnected:
connection = true;
break;
case NetworkNotificationType.InterfaceDisconnected:
info = "Lost Internet";
disco=true;
break;
case NetworkNotificationType.CharacteristicUpdate:
break;
default:
break;
}
Dispatcher.BeginInvoke(() =>
{
if(disco)
MessageBox.Show(info);
if(connection)
webbrowser1.Navigate(site);
});
}
I have question i check in phone that these methods IsCellularDataEnabled, IsNetworkAvailable, IsWiFiEnabled return true. I read somewhere that event NetworkAvailabilityChanged only work when is only one type of network is enable. Is this true?

Please check this page it may help you http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.devicenetworkinformation.networkavailabilitychanged(v=vs.92).aspx you can take the information of disconnected from NetworkNotificationEventArgs argument as it says...

Related

Trouble with connecting to wifi in code in Xamarin

I've been trying to connect to a specific wifi through code, but with no succcess.
This is what i've come up with:
public void ConnectToWifi(string ssid, string password)
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
if (!wifiManager.IsWifiEnabled)
{
wifiManager.SetWifiEnabled(true);
}
string formattedSsid = $"\"{ssid}\"";
string formattedPassword = $"\"{password}\"";
WifiConfiguration wifiConfig = new WifiConfiguration
{
Ssid = formattedSsid,
PreSharedKey = formattedPassword
};
var addNetwork = wifiManager.AddNetwork(wifiConfig);
WifiConfiguration network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == ssid);
if (network == null)
{
Console.WriteLine($"Cannot connect to network: {ssid}");
return;
}
wifiManager.Disconnect();
bool enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
}
I've added permissions.
When testing it does turn the wifi on atleast, so i know it works until that point. What seems not to be working is the AddNetwork part.
I appreciate any help i can get!
You are missing one key method - reconnect(). You can read more about it in the WifiManager's docs here
The important part of the documentation is:
Reconnect to the currently active access point, if we are currently disconnected.
So, what you need to do it after you have disconnected and enabled your new network, call in the end this and you will be good to go:
wifiManager.Disconnect();
wifiManager.EnableNetwork(network.NetworkId, true);
wifiManager.Reconnect(); // This is the missing method
NB: Keep in mind that most of the WifiManager's code that you are using is being obsolete starting Android 10. So, if you want to target Android 10, then you will need to write an additional code for the connectivity for devices with Android 10+.

Detect network changes in Xamarin Forms

I want to detect when the user is online or offline.
I am using CrossConnectivity package to detect connectivity changes.
I have to connect to VPN (Sonic Wall to be exact) in order to connect to my server.
My problem is this: When I am connecting to my server, I need to switch apps in order for me to connect to my server. When I switch back to my app the function SyncFunction.SyncUser(host, database, contact, ipaddress, pingipaddress) is not executing. The connectivity changed function is not on my App.xaml.cs it is on my Main Menu Content page because I need the sync function to be executed in my main menu not the whole app. How can I fix this?
CrossConnectivity.Current.ConnectivityChanged += async (sender, args) =>
{
var appdate = Preferences.Get("appdatetime", String.Empty, "private_prefs");
if (string.IsNullOrEmpty(appdate))
{
Preferences.Set("appdatetime", DateTime.Now.ToString(), "private_prefs");
}
else
{
if (DateTime.Now >= DateTime.Parse(Preferences.Get("appdatetime", String.Empty, "private_prefs")))
{
Preferences.Set("appdatetime", DateTime.Now.ToString(), "private_prefs");
if (CrossConnectivity.Current.IsConnected)
{
var ping = new Ping();
var reply = ping.Send(new IPAddress(pingipaddress), 5000);
if (reply.Status == IPStatus.Success)
{
lblStatus.Text = "Syncing data to server";
lblStatus.BackgroundColor = Color.FromHex("#2bcbba");
await Task.Delay(5000);
SyncFunction.SyncUser(host, database, contact, ipaddress, pingipaddress);
lblStatus.Text = "Online - Connected to server";
lblStatus.BackgroundColor = Color.FromHex("#2ecc71");
}
else
{
lblStatus.Text = "Online - Server unreachable. Connect to VPN";
lblStatus.BackgroundColor = Color.FromHex("#e67e22");
}
}
else
{
lblStatus.Text = "Offline - Connect to internet";
lblStatus.BackgroundColor = Color.FromHex("#e74c3c");
}
}
else
{
await DisplayAlert("Application Error", "It appears you change the time/date of your phone. Please restore the correct time/date", "Got it");
await Navigation.PopToRootAsync();
}
}
};
Detecting connectivity change across a VPN is not easy.
A workaround solution is to use a webservice as ping.
If you have a backend with API, this "ping" can be executed regularly to ensure the network AND the API are accessible.
This solution is to be used in addition to the connectivity check
Subscribe to connectivity changed
When conectivity looks OK, check the "ping service"
Typically in a mob app, this "ping endpoint" can be something like "/about".
Moreover, this specific service can be use to perform the compatibility version check beetween App Mob version and API version.
(look also Xamarin.Essentials to replace CrossConnectivity by Xamarin.Essentials: Connectivity, https://learn.microsoft.com/fr-fr/xamarin/essentials/connectivity?context=xamarin%2Fxamarin-forms&tabs=android)

How to check internet connection continuously in Xamarin.Android Native?

My application is completely based on internet and it does not work without it, when the internet is not available or it is slow my application is getting stopped unfortunately.
I tried to implement try, catch but it is not helping me out as it is not throwing any exception, then I thought that I have to check the internet connectivity continuously till the app is running and stop any activity from performing and set a popup to connect to the internet.
I am able to get the popup whenever I call a method which has the following code inside it,
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
if (networkInfo == null)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Network");
alert.SetMessage("Please turn of your Wifi or Mobile Data From Settings");
alert.SetPositiveButton("OK", (senderAlert, args) => {
Intent intent = new Intent(Android.Provider.Settings.ActionSettings);
StartActivity(intent);
});
alert.SetNegativeButton("Cancel", (senderAlert, args) => {
Toast.MakeText(this, "Cancelled!", ToastLength.Short).Show();
Finish();
});
Dialog dialog = alert.Create();
dialog.Show();
But I am unable to get the connection checked continuously, So Can some one Please help me to complete get this functionality in my application.
You need to use a BroadcastReceiver to monitor network changes.
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "android.net.conn.CONNECTIVITY_CHANGE" })]
[Android.Runtime.Preserve(AllMembers = true)]
public class ConnectivityChangeBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action != ConnectivityManager.ConnectivityAction)
return;
//Check if is connected and raise a custom event or store
//the current in a static global variable
}
}
}
In Android 7.0, you need to remove IntentFilter from the class and register the receiver.
var receiver = new ConnectivityChangeBroadcastReceiver();
Application.Context.RegisterReceiver(receiver, new IntentFilter(ConnectivityManager.ConnectivityAction));
Another option is to use the ConnectivityPlugin https://github.com/jamesmontemagno/ConnectivityPlugin , which is easier to use.
CrossConnectivity.Current.ConnectivityChanged += HandleConnectivityChanged;
void HandleConnectivityChanged (object sender, ConnectivityChangedEventArgs e)
{
// You can check the network status in
//e.IsConnected
}
Note that The ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE permissions are required.

Telerik Winforms Reports freeze on Terminal Services

I am using Telerik reports in our app and it is being accessed mostly through an RDP session running in "app mode". Everything works fine locally but when I put it on the TS machine it freezes after the print dialog comes up.
The standard print dialog comes up and you can choose the printer and hit ok but then a small box opens with header of Printing... and then never does anything.
I am not sure what code to post since its fine locally, let me know what you want to see. also printing other things like the Telerik grids and charts are fine.
Found the answer on my own.
I created a standard printdialog screen and "rolled my own" print method and all seems to be good. Hope this helps someone else.
private void reportViewer1_Print(object sender, CancelEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
e.Cancel = true;
try
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
var result = pd.ShowDialog();
if (result ==DialogResult.OK)
{
// Print the report using the custom print controller
var reportProcessor
= new Telerik.Reporting.Processing.ReportProcessor();
reportProcessor.PrintReport(this.reportViewer1.ReportSource, pd.PrinterSettings);
}
}
catch (Exception ex)
{
Program.ExceptionHandler(ex);
}
this.Cursor = Cursors.Default;
}

Disabling certain options in Visual Studio 2010, when one option is selected

Hi guys Im using Visual Studio 2010 C sharp.
Basically Im building a program and I want to be able to disable certain options after one option is selected. For example when you fill out an online form for something like a job application and it asks do you have a degree? If you select no then the next options below related to the degree question are disabled. That is what I basically want to do.
I couldnt upload the image im affraid :(
Basically as you can see, what I want to do when RDP is selected the 'Site URL' becomes disabled but when any of the other web browser options are selected the 'RDP Connection' is disabled.
Thanks
Hi I figured out how to do this, I thought I would post it here in case it would be any help to anyone else/
Basically it was the use of just and if statement -_-" (cant believe I didnt think of it)
Basically below is a section of my script associated with the combo box I made. There are two options in the combo box, one if internet connection and one is RDP connection. When either one is selected it will 'hide' or 'show' certain data boxes below.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "Internet Browser")
{
label4.Visible = false;
comboBox2.Visible = false;
btnCreate.Visible = false;
label5.Visible = true;
textBox3.Visible = true;
}
else
{
label4.Visible = true;
comboBox2.Visible = true;
btnCreate.Visible = true;
label5.Visible = false;
textBox3.Visible = false;
}
}
Its basic boolean, if you have any problems, message me and I will help. Happy coding =)

Resources