Getting internet connection status from WinRT - c#

Below if the code I've been using for some time to get the connection status of the device that my store app in running on. What appears to have happened recently is, whilst it still finds the correct connection profile, it returns the level as Local, rather than Internet access.
IReadOnlyList<ConnectionProfile> p = NetworkInformation.GetConnectionProfiles();
foreach (ConnectionProfile prof in p)
{
NetworkConnectivityLevel lev = prof.GetNetworkConnectivityLevel();
if (lev == NetworkConnectivityLevel.InternetAccess)
{
return true;
}
}
return false;
Can anyone tell me why this might be, and how I can persuade it that I do, in fact, have a working internet connection (which I can prove by being able to post this question :-) )?

try this one
private bool roaming;
private string connectionProfileInfo;
private async Task<bool> IsConnectedToInternet()
{
HttpWebRequest webReq;
HttpWebResponse resp = null;
// HttpStatusCode respcode;
Uri url = null;
url = new Uri("http://www.dartinnovations.com");
webReq = (HttpWebRequest)WebRequest.Create(url);
try
{
resp = (HttpWebResponse)await webReq.GetResponseAsync();
// Debug.WriteLine(resp.StatusCode);
webReq.Abort();
webReq = null;
url = null;
resp = null;
return true;
}
catch
{
webReq.Abort();
webReq = null;
return false;
}
}
private async Task<bool> CheckForConnection()
{
bool isConnected = await IsConnectedToInternet();
Debug.WriteLine(isConnected);
ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (isConnected)
{
if (internetConnectionProfile != null)//Gets metereing info, Connectionprofile gives false positives when used to check for internet connectivity
{
Debug.WriteLine("internet available");
GetMeteringInformation(internetConnCectionProfile);
}
else
{
connectionProfileInfo = "Roaming information not available";
roaming = false;
// Debug.WriteLine("no connections");
}
return true;
}
return false;
}
private async Task GetMeteringInformation(ConnectionProfile connectionProfile)
{
ConnectionCost connectionCost = connectionProfile.GetConnectionCost();
roaming = connectionCost.Roaming;
connectionProfileInfo = "Over Data Limit :" + connectionCost.OverDataLimit + " | Approaching Data Limit :" +
connectionCost.ApproachingDataLimit;
}

Related

How to catch and handle GetBytesAsync error when offline using Firebase Storage?

I have a Firebase app where I download images. I'm working on how the app would react when offline. With my DownloadImage Method I get an error that I can't seem to properly catch and handle:
ApplicationException: GetFutureStatus(handle) == kFutureStatusPending Rethrow as ApplicationException: backing->status != kFutureStatusComplete
I know the DownloadImage shouldn't work, because I'm offline. However, I can't seem to catch and handle this error, so that the rest of my code can continue.
This is my code for the DownloadImage Method:
public static async Task<ImageCallback> DownloadImage(ArchProject project, ImageSector sector, string fileName)
{
ImageCallback _callback = new ImageCallback();
const long maxAllowedSize = 1 * 2048 * 2048;
StorageReference img_ref = storage.RootReference.Child(ProjectsKey).Child(project.data.ID)
.Child(ImagesKey).Child(sector.ToString()).Child(fileName);
if (Application.internetReachability == NetworkReachability.NotReachable)
{
_callback.isSuccess = false;
_callback.errorMessage = "Please connect to the internet to download images";
return _callback;
}
return await img_ref.GetBytesAsync(maxAllowedSize).ContinueWith((Task<byte[]> task) =>
{
if (task.IsFaulted || task.IsCanceled)
{
_callback.isSuccess = false;
if (task.Exception != null)
_callback.errorMessage = task.Exception.ToString();
else
_callback.errorMessage = "Unable to connect";
_callback.fileName = fileName;
return _callback;
}
else
{
byte[] fileContents = task.Result;
_callback.isSuccess = true;
_callback.fileName = fileName;
_callback.imageBytes = fileContents;
return _callback;
}
});
}
(I bypass the internetReachability check to see how it would react if the device thinks it has internet, but actually doesn't. That is when I get the error)
Can anyone explain where the error comes from and how I can catch/handle it properly?

How to check valid URL address?

I have simple code , wich get url path and redirect to this url:
private void Redirect(String path)
{
Uri validatedUri = null;
var result = Uri.TryCreate(HelpURL + path, UriKind.Absolute, out validatedUri);
if (result&&validatedUri!=null)
{
var wellFormed = Uri.IsWellFormedUriString(HelpURL + path, UriKind.Absolute);
if(wellFormed)
{
Response.Write("Redirect to: " + HelpURL + path);
Response.AddHeader("REFRESH", "1;URL=" + HelpURL + path);
}
else //error
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
else
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
Example of Url:http://web-server/SomeSystemindex.html. It is not valid address, but:
at my code result is true, wellFormed is true too!
How to validate url address?
P.S. HelpUrl+path=http://web-server/SomeSystemindex.html for this case. Where HelpUrl is 'http://web-server/SomeSystem', and path=index.html
P.P.S. I do as Martin says- create connection and check the status code.
HttpWebRequest req = WebRequest.Create(HelpURL + path) as HttpWebRequest;
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
var statusCode= ((HttpWebResponse)req.GetResponse()).StatusCode;
if (statusCode == HttpStatusCode.NotFound)
isValid = false;
else if (statusCode == HttpStatusCode.Gone)
isValid = false;
else
{
isValid = true;
}
As far as I know, the only way to determine whether an address is valid or not, is by opening a connection. If the connection lives, the address is valid. If not, the connection is not valid. There are some tricks to filter out bad URL's, but to know whether an adress is valid, you need to open a connection.
An example has already been posted on StackOverflow here
Or here:
URL url;
URL wrongUrl;
try {
url = new URL("http://google.com");
wrongUrl = new URL( "http://notavalidurlihope.com");
HttpURLConnection con = (HttpURLConnection ) url.openConnection();
System.out.println(con.getResponseCode());
HttpURLConnection con2 = (HttpURLConnection ) wrongUrl.openConnection();
System.out.println(con2.getResponseCode());
} catch (IOException e) {
System.out.println("Error connecting");
}
Note: Do disconnect afterwards
output:
200
Error connecting
This simple helper method uses regex to ensure that a website URL is in correct format. It will also fail if there is any white space (which is important).
The following URL's pass:
google.com
www.google.com
http://google.com
http://www.google.com
https://google.com/test/test
https://www.google.com/test
It fails on:
www.google.com/a bad path with white space/
Below is the helper method I created:
public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
Regex pattern = new Regex(#"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]#!\$&'\(\)\*\+,;=.]+$");
Match match = pattern.Match(value);
if (match.Success == false) return false;
return true;
}

Remembering log in credentials/permissions UWP/C# (Microsoft Cloud API)

I'm creating an app that access the Microsoft Cloud API to get health data. It uses OAuth to log in when you hit the Sign In Button
private void signinButton_Click(object sender, RoutedEventArgs e)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_authorize.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&scope={0}", Uri.EscapeDataString(Scopes));
query.Append("&response_type=code");
uri.Query = query.ToString();
this.webView.Visibility = Visibility.Visible;
this.webView.Navigate(uri.Uri);
}
This brings up a webView with the page to log in using Microsoft credentials. Once completed, it leads to this:
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
//
// When the web view navigates to our redirect URI, extract the authorization code from
// the URI and use it to fetch our access token. If no authorization code is present,
// we're completing a sign-out flow.
//
if (args.Uri.LocalPath.StartsWith("/oauth20_desktop.srf", StringComparison.OrdinalIgnoreCase))
{
WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args.Uri.Query);
var code = decoder.FirstOrDefault((entry) => entry.Name.Equals("code", StringComparison.OrdinalIgnoreCase));
var error = decoder.FirstOrDefault((entry) => entry.Name.Equals("error", StringComparison.OrdinalIgnoreCase));
var errorDesc = decoder.FirstOrDefault((entry) => entry.Name.Equals("error_description", StringComparison.OrdinalIgnoreCase));
// Check the code to see if this is sign-in or sign-out
if (code != null)
{
// Hide the browser again, no matter what happened...
sender.Visibility = Visibility.Collapsed;
if (error != null)
{
this.responseText.Text = string.Format("{0}\r\n{1}", error.Value, errorDesc.Value);
return;
}
var tokenError = await this.GetToken(code.Value, false);
if (string.IsNullOrEmpty(tokenError))
{
this.responseText.Text = "Successful sign-in!";
this.signoutButton.IsEnabled = true;
this.signinButton.IsEnabled = false;
this.getProfileButton.IsEnabled = true;
this.getDevicesButton.IsEnabled = true;
this.getActivitiesButton.IsEnabled = true;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = true;
}
else
{
this.responseText.Text = tokenError;
}
}
else
{
this.responseText.Text = "Successful sign-out!";
this.signoutButton.IsEnabled = false;
this.signinButton.IsEnabled = true;
this.getProfileButton.IsEnabled = false;
this.getDevicesButton.IsEnabled = false;
this.getActivitiesButton.IsEnabled = false;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = false;
}
}
}
private async Task<string> GetToken(string code, bool isRefresh)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_token.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&client_secret={0}", Uri.EscapeDataString(ClientSecret));
if (isRefresh)
{
query.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=refresh_token");
}
else
{
query.AppendFormat("&code={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=authorization_code");
}
uri.Query = query.ToString();
var request = WebRequest.Create(uri.Uri);
try
{
using (var response = await request.GetResponseAsync())
{
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
var responseString = streamReader.ReadToEnd();
var jsonResponse = JObject.Parse(responseString);
this.creds.AccessToken = (string)jsonResponse["access_token"];
this.creds.ExpiresIn = (long)jsonResponse["expires_in"];
this.creds.RefreshToken = (string)jsonResponse["refresh_token"];
string error = (string)jsonResponse["error"];
return error;
}
}
}
}
catch (Exception ex)
{
return ex.Message;
}
}
I don't want users to have to accept the permissions every time the app is launched. Is there a way to save credentials locally so that it automatically authenticates on launch? Thanks!
You can use
Windows.Storage.ApplicationData.Current.LocalSettings
This process good described by this answer Best Way to keep Settings for a WinRT App?
The code in link identity to UWP
Store the needed oauth parts in the credential locker API. Never store these kind of information in the normal settings API.
On start read the oauth information and use the refreshtoken to get a new access token.
More Information here.
https://msdn.microsoft.com/en-us/library/windows/apps/mt270189.aspx

Why ExpenseLineRetList return null

I saw this link and I notice we have the same problem, and his question still didn't answer yet.
Here is the question.
public class ServiceSel
{
public void GetCheqe()
{
bool sessionBegun = false;
bool connectionOpen = false;
QBSessionManager rp = null;
try
{
rp = new QBSessionManager();
IMsgSetRequest requestMsgSet = rp.CreateMsgSetRequest("US", 8, 0);
requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
rp.OpenConnection("Database Path File QuickBooks", "QuickBooks Integration Demo");
connectionOpen = true;
rp.BeginSession("", ENOpenMode.omDontCare);
sessionBegun = true;
ICheckQuery checkQuery = requestMsgSet.AppendCheckQueryRq();
IMsgSetResponse msgSetRs = rp.DoRequests(requestMsgSet);
IResponse response = msgSetRs.ResponseList.GetAt(0);
ICheckRetList checkRetList = (ICheckRetList)response.Detail;
if (checkRetList != null)
{
for (int i = 0; i < checkRetList.Count; i++)
{
ICheckRet checkRet = checkRetList.GetAt(i);
//Bank Account On top
string TxnID = checkRet.TxnID.GetValue().ToString(); //Data correct
string TxnNumber = checkRet.TxnNumber.GetValue().ToString(); //Data correct
string Account = checkRet.AccountRef.FullName.GetValue(); //Data correct
string Amount = checkRet.Amount.GetValue().ToString(); //Data correct
if (checkRet.ExpenseLineRetList != null)
{
Error checkRet.Expense Show null Data But in quickbooks have many data expense in calendar
}
}
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Error");
}
finally
{
if (sessionBegun)
{
rp.EndSession();
}
if (connectionOpen)
{
rp.CloseConnection();
}
}
}
Why ExpenseLineRetList is null?
A check request will not include the detail lines of the check unless you include it in your query. By adding the IncludeLineItems setting, you'll get access to the Expense or Item lists of the check (a check could have Expense lines, Item lines, or both). You'll want to change to include the following:
ICheckQuery checkQuery = requestMsgSet.AppendCheckQueryRq();
checkQuery.IncludeLineItems.SetValue(true);
IMsgSetResponse msgSetRs = rp.DoRequests(requestMsgSet);
I would also suggest that you check the response code before trying to get the response detail so you can better handle errors:
IResponse response = msgSetRs.ResponseList.GetAt(0);
if(response.StatusCode != 0)
{
// There was an error. response.StatusCode has the error number
// response.StatusMessage has the error description.
}
else
{
ICheckRetList checkRetList = (ICheckRetList)response.Detail;
.
.
.
}

How to test if a proxy server is working or not?

I've got a pretty big list with proxy servers and their corresponding ports. How can I check, if they are working or not?
Working? Well, you have to use them to see if they are working.
If you want to see if they are online, I guess ping is a first step.
There is a Ping class in .NET.
using System.Net.NetworkInformation;
private static bool CanPing(string address)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(address, 2000);
if (reply == null) return false;
return (reply.Status == IPStatus.Success);
}
catch (PingException e)
{
return false;
}
}
I like to do a WhatIsMyIP check through a proxy as a test.
using RestSharp;
public static void TestProxies() {
var lowp = new List<WebProxy> { new WebProxy("1.2.3.4", 8080), new WebProxy("5.6.7.8", 80) };
Parallel.ForEach(lowp, wp => {
var success = false;
var errorMsg = "";
var sw = new Stopwatch();
try {
sw.Start();
var response = new RestClient {
//this site is no longer up
BaseUrl = "https://webapi.theproxisright.com/",
Proxy = wp
}.Execute(new RestRequest {
Resource = "api/ip",
Method = Method.GET,
Timeout = 10000,
RequestFormat = DataFormat.Json
});
if (response.ErrorException != null) {
throw response.ErrorException;
}
success = (response.Content == wp.Address.Host);
} catch (Exception ex) {
errorMsg = ex.Message;
} finally {
sw.Stop();
Console.WriteLine("Success:" + success.ToString() + "|Connection Time:" + sw.Elapsed.TotalSeconds + "|ErrorMsg" + errorMsg);
}
});
}
However, I might suggest testing explicitly for different types (ie http, https, socks4, socks5). The above only checks https. In building the ProxyChecker for https://theproxisright.com/#proxyChecker, I started w/ the code above, then eventually had to expand for other capabilities/types.
try this:
public static bool SoketConnect(string host, int port)
{
var is_success = false;
try
{
var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
System.Threading.Thread.Sleep(500);
var hip = IPAddress.Parse(host);
var ipep = new IPEndPoint(hip, port);
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
string strIP = "10.0.0.0";
int intPort = 12345;
public static bool PingHost(string strIP , int intPort )
{
bool blProxy= false;
try
{
TcpClient client = new TcpClient(strIP ,intPort );
blProxy = true;
}
catch (Exception ex)
{
MessageBox.Show("Error pinging host:'" + strIP + ":" + intPort .ToString() + "'");
return false;
}
return blProxy;
}
public void Proxy()
{
bool tt = PingHost(strIP ,intPort );
if(tt == true)
{
MessageBox.Show("tt True");
}
else
{
MessageBox.Show("tt False");
}

Categories

Resources