Anyone know a good way to see if the user is online/offline? When I use public static bool IsConnectedToNetwork(); and see if it's false/true it seems to always be true, even when I shut down my internet to test it...
Am I missing something?
public static bool nets()
{
bool go =
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (go == false)
{
return false;
}
return true;
}
Now, in my start-up I run:
var ba = nets();
if (ba == false)
{
txtHeader.Text = "err";
}
if (ba != false)
{
// Code
}
I also tried:
public static bool IsConnectedToNetwork();
I use
public static bool IsConnectedToInternet()
{
ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile();
return (connectionProfile!=null && connectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
}
You could ping one of the few well known URLs to see if you get responses.
I have a way that seems to work pretty decent, especially noticing sometimes Ethernet could appear to be in use even when its not in Windows 8 RTM... That's why nothing seems to work!
However, doing the following is a good choice for me to test...
var profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
var interfaceType = profile.NetworkAdapter.IanaInterfaceType;
// 71 is WiFi & 6 is Ethernet
if (interfaceType == 71 | interfaceType == 6)
{
// Run Code
}
/* 3G/Mobile Detect
else if (interfaceType == 243 | interfaceType == 244)
{
// Run Code if you need to use a less quality feature.
}*/
else
{
txtHeader.Text = "Error, Check connection or Try connecting to the Internet...";
}
Related
I have a very odd issue that is happening when pinging a large amount of proxies. The "RoundTripTime" is returning 0 randomly.
If I run the proxy list through the checker a second time it will have different proxies returning up 0 and others returning with actual ms.
I thought this was maybe due to it being too many requests at once so I tried adding some manual sleep into it but that caused more "0" response times.
I'm seriously stuck and appreciate all help.
public static List<string> proxyList = new List<string>();
public static List<string> proxyNoPort = new List<string>();
public static int proxyCount;
public static int proxyTimeOut;
public static long pingResponseTime;
public static bool proxyTest()
{
try
{
Ping pingTest = new Ping();
PingReply pingResponse = pingTest.Send(proxyNoPort[proxyCount], proxyTimeOut);
if (pingResponse != null && pingResponse.RoundtripTime < proxyTimeOut)
{
pingResponseTime = pingResponse.RoundtripTime;
return true;
}
}
catch
{
proxyList.Remove(proxyList[proxyCount]);
proxyNoPort.Remove(proxyNoPort[proxyCount]);
return false;
}
return false;
}
[Picture of program][1]
[1]: https://i.stack.imgur.com/M0Nar.png
Notes from my own further testing:
If the number returns "0" making it re-ping the same proxy works for about 90% of the proxies.
if(pingResponse.RoundtripTime == 0)
{
pingResponse = pingTest.Send(proxyNoPort[proxyCount], proxyTimeOut);
pingResponseTime = pingResponse.RoundtripTime;
}
Turns out that using code from this forum isn't always the best and you should maybe look into the official documents. It turns out when the pings response is "0" that means it has failed to connect.
I fixed my code completely by replacing
if (pingResponse != null && pingResponse.RoundtripTime < proxyTimeOut)
{
pingResponseTime = pingResponse.RoundtripTime;
return true;
}
with
if (pingResponse.Status == IPStatus.Success && pingResponse.RoundtripTime < proxyTimeOut)
{
pingResponseTime = pingResponse.RoundtripTime;
return true;
}
Although not all is bad as the use "Dai" informed me I should be using the "Using" tags and that has sped up my proxy checking significantly, thanks!
I'm trying to detect if the website is running in local to display the stack trace instead of a nice server error page. I've been happily using Request.IsLocal in the Global.asax.cs file locally and on internal environments, but when it gets deployed to an Azure app it behaves as if the request was indeed local.
According to the documentation this actually checks if the originating IP was 127.0.0.1 but I don't understand how can that be. Is this just some weird Azure underlying problem?
I didn't see same problem. But, I think, you can try doing IsLocal with the following code.
public static class HttpRequestExtensions
{
public static bool IsLocal(this HttpRequest req)
{
var connection = req.HttpContext.Connection;
if (connection.RemoteIpAddress != null)
{
if (connection.LocalIpAddress != null)
{
return connection.RemoteIpAddress.Equals(connection.LocalIpAddress);
}
return IPAddress.IsLoopback(connection.RemoteIpAddress);
}
if (connection.RemoteIpAddress == null && connection.LocalIpAddress == null)
{
return true;
}
return false;
}
}
Why System.Net.ServicePoint.ConnectionLimit uses '7FFFFFFF' (Int32.MaxValue/2147483647) when a client connects to a service on 'localhost', whereas it decide to use '2' as default if the service is running on remote machine?
Initially I thought it will be ServicePointManager.DefaultConnectionLimit if servicepoint.connectionlimit is not set. However, I just realized (once I got an issue from customer), that its Int32.MaxValue/2147483647.
I have done some research (for details please refer to below links), however I couldn't find out why it uses to int32.maxvalue. I can kind of conjecture its probably for better performance as the input requests and response messages are not going across boundary.
My Question(s):
Why Int32.MaxValue if the service is running on 'localhost'?
(any explanation in English ;) of the code snippet I copied from reflector is also great - as I kind of conjectured the intentions - but didn't understand the code totally :))
I understand its for perf - but from '2' (default) to 'int32.maxvalue' sounds stretch to me. In other words why is it ok to open as many TCP connections as long as the requests are not going across network.
(in other words - why default to int32.maxvalue - doesn't it have side affects)
Some useful links related to this:
How and where the TCP connection has been created in httpwebrequest, and how is it related to servicepoint?
http://blogs.microsoft.co.il/idof/2011/06/20/servicepointmanagerdefaultconnectionlimit-2-depends/
http://msdn.microsoft.com/en-us/library/system.net.servicepoint.connectionlimit(v=vs.110).aspx
http://arnosoftwaredev.blogspot.com/2006/09/net-20-httpwebrequestkeepalive-and.html
Code Snippet from Reflector
public int ConnectionLimit
{
get
{
if ((!this.m_UserChangedLimit && (this.m_IPAddressInfoList == null)) && (this.m_HostLoopbackGuess == TriState.Unspecified))
{
lock (this)
{
if ((!this.m_UserChangedLimit && (this.m_IPAddressInfoList == null)) && (this.m_HostLoopbackGuess == TriState.Unspecified))
{
IPAddress address = null;
if (IPAddress.TryParse(this.m_Host, out address))
{
this.m_HostLoopbackGuess = IsAddressListLoopback(new IPAddress[] { address }) ? TriState.True : TriState.False;
}
else
{
this.m_HostLoopbackGuess = NclUtilities.GuessWhetherHostIsLoopback(this.m_Host) ? TriState.True : TriState.False;
}
}
}
}
if (!this.m_UserChangedLimit && !((this.m_IPAddressInfoList == null) ? (this.m_HostLoopbackGuess != TriState.True) : !this.m_IPAddressesAreLoopback))
{
return 0x7fffffff;
}
return this.m_ConnectionLimit;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("value");
}
if (!this.m_UserChangedLimit || (this.m_ConnectionLimit != value))
{
lock (this)
{
if (!this.m_UserChangedLimit || (this.m_ConnectionLimit != value))
{
this.m_ConnectionLimit = value;
this.m_UserChangedLimit = true;
this.ResolveConnectionLimit();
}
}
}
}
}
Regards,
Int32.maxvalue is just a placeholder for no limit. You should be able to create as many connections to yourself as you need to.
The code you pasted basically just checks whether you are connecting to the loopback address or not, and if you are, returns maxint, if you are not, returns the value of servicepoint.connectionlimit (2 by default, but you can change it)
Is there a way to quickly check the following logic in C#?
if (a)
{
}
if (b)
{
}
if (c)
{
}
else //none of the above, execute if all above conditions are false
{
/* do something only if !a && !b && !c */
}
This differs from using if-else in that a, b, and c can all be true at once, so I can't stack them that way.
I want to run the else block when a, b, and c are all false without writing if (!a && !b && !c). This is because the code can get quite messy when the if conditions become more complex. It requires rewriting a lot of code.
Is this possible?
Firstly, no, else blocks only respect the if clause immediately above them, so you'll need an alternative.
This option isn't especially "clean", but I'd do:
bool noneAreTrue = true;
if(a)
{
noneAreTrue = false;
}
if(b)
{
noneAreTrue = false;
}
if(c)
{
noneAreTrue = false;
}
if(noneAreTrue)
{
//execute if all above conditions are false
}
Also, if your conditions are really pretty big, I recommend the rule G28 (Encapsulate Conditionals) from the book Clean Code from Robert C. Martin.
It is pretty verbose, but can be easier to read in some instances:
public void YourMethod()
{
if(SomeComplexLogic())
{
}
if(SomeMoreLogic())
{
}
if(EvenMoreComplexLogic())
{
}
if(NoComplexLogicApply())
{
}
}
private bool SomeComplexLogic(){
return stuff;
}
private bool EvenMoreComplexLogic(){
return moreStuff;
}
private bool EvenMoreComplexLogic(){
return evenMoreStuff;
}
private bool NoComplexLogicApply(){
return SomeComplexLogic() && EvenMoreComplexLogic() && EvenMoreComplexLogic();
}
How about combine the concepts of Strategies and Specifications
var strategies = _availableStrategies.All(x => x.IsSatisfiedBy(value));
foreach (var strategy in strategies)
{
strategy.Execute(context);
}
if (!strategies.Any()) {
// run a different strategy
}
Rather than encapsulate some complex condition in a method that you will only ever call once or twice, I would just keep in a variable. This is also more readable than using some marker boolean as other answers suggest.
A contrived example,
bool isBlue = sky.Color == Colors.Blue;
bool containsOxygen = sky.Atoms.Contains("oxygen") && sky.Bonds.Type == Bond.Double;
bool canRain = sky.Abilities.Contains("rain");
if(isBlue)
{
}
if(containsOxygen)
{
}
if(canRain)
{
}
if(!isBlue && !containsOxygen && !canRain)
{
}
Now we have abstracted what might otherwise be complex conditions into readable English!
What is the best way in c# to determine whether the programmer is running the program via IDE or its user?
if (System.Diagnostics.Debugger.IsAttached) {
// You are debugging
}
public static bool IsInVisualStudio
{
get
{
bool inIDE = false;
string[] args = System.Environment.GetCommandLineArgs();
if (args != null && args.Length > 0)
{
string prgName = args[0].ToUpper();
inIDE = prgName.EndsWith("VSHOST.EXE");
}
return inIDE;
}
}