How to detect if connection is unsuccessful using Watin? - c#

I have a project about going to a website. If the website cannot because of several reasons, such as not being connected to the Internet, wrong proxy ip, etc, the browser will show a page with text "You're not connected to a network". In this situation, I want to auto refresh the browser. How will the program detect that website can't be loaded?
Take a look at my below code:
public void exam()
{
var ie = new IE();
ie.GoTo("http://search.yahoo.com");
ie.WaitForComplete(5);
if (ie.ContainsText("You're not connected to a network"))
{
ie.Close();// or ie.Refresh()
}
}
It doesn't work.

Try testing to see if you can Ping the address first ... try using this
public bool CanConnect()
{
var ping = new Ping();
var reply = ping.Send("search.yahoo.com");
return reply.Status == IPStatus.Success;
}
or if you want to pass the address as a parameter:
public bool CanConnect(string addressToTest)
{
var ping = new Ping();
var reply = ping.Send(addressToTest);
return reply.Status == IPStatus.Success;
}

Related

How to get remote host status by using Connectivity Plugin 4.0?

I want to ping remote host and get his status I created function like this:
public async Task<Boolean> Connect_Test(string ip,int port)
{
var isReachable = await CrossConnectivity.Current.IsReachable(ip, port);
if (isReachable == true)
{
return true;
}
else
{
return false;
}
}
I call this function like this:
var connect = Connect_Test(adres_ip, 4210).Result;
if (connect==true)
{
//Alert is reachable
}
else
{
//Alert not reachable
}
My app freezes after executing this code and don't return value of of the remote host status.
I used wrong method from connectivity plugin the correct one is IsRemoteReachable. Problem is solved.

Verify not only internet connection but if it is passing data - XAMARIN

I'm having a problem with this verification of the internet connection. See I have this verification in my code:
if (CrossConnectivity.Current.IsConnected)
{
...
}
It works, but I think there is a situation that this do not cover, I have a shopping right next door to my office, I enter the shopping and the device just connects with the shopping WI-FI, but it's not passing data, because it need's to login in the session to get free WI-FI from the shopping.
So my question in resume is, is there a way, not only to verify if the device is conected to the internet, but if it is passing data through the connection?
I didn't try this solution but it might help you.
if (CrossConnectivity.Current.IsConnected)
{
if (ConnectGoogle())
{
return true;
}
else
{
//
}
}
ConnectGoogle method
public bool ConnectGoogle()
{
try
{
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").OpenConnection());
urlc.SetRequestProperty("User-Agent", "Test");
urlc.SetRequestProperty("Connection", "close");
urlc.ConnectTimeout = 10000;
urlc.Connect();
return (urlc.ResponseCode == HttpStatus.Accepted);
}
catch (Exception ex)
{
//Log(ex.Message);
return false;
}
}
You could use System.Net.WebClient and test open/read an url. Also another way could be to ping a resource that is theoritically never offline. i.e. google.
Something like:
if (CrossConnectivity.Current.IsConnected)
{
try {
Ping ping = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = ping.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success){
// Your code here...
}
}
catch (Exception) {
return false;
}
}
Hope it helps.
Thanks everyone, I see all answers work in my situation, but I used this method from https://jamesmontemagno.github.io/ConnectivityPlugin/PingaHost.html, you could open it or just see it down here:
var verificaPassagemDados = await CrossConnectivity.Current.IsRemoteReachable("google.com");
Thanks #sme

c# websphere set local port on windows tcp

I'm using the IBM websphere XMS API to connect and send messages to the mainframe. However, every message sent is sent through a new local port. Is there a way to set this to a fixed port?
A new port is created locally when the following line is hit:
var connContext = new XMSConnectionContext(connFactory.CreateConnection(), sendQ, replyQ, mqProfile, DateTime.Now.AddSeconds(qm.MqConfiguration.ConnectionPoolExpiryTime));
The code I'm using is
public IMQMessage Message { get; set; }
public void Initialise(IMQMessage message, QueueSet queueSet, QueueManager queueManager)
{
Message = message;
if (_connContext.ContainsKey(message.MessageId)) return;
_connContext.TryAdd(message.MessageId, ConnectQueueSet(queueSet, queueManager));
_connContext[message.MessageId].Connection.Start();
}
private XMSConnectionContext ConnectQueueSet(MQQueueSet queueSet, QueueManager qm)
{
var mqProfile = GetProfile(queueSet);
var xmsFactory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
var connFactory = xmsFactory.CreateConnectionFactory();
connFactory.SetStringProperty(XMSC.WMQ_HOST_NAME, mqProfile.ServerName);
connFactory.SetIntProperty(XMSC.WMQ_PORT, mqProfile.Port);
connFactory.SetStringProperty(XMSC.WMQ_CHANNEL, mqProfile.ChannelName);
connFactory.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, mqProfile.QueueManagerName);
connFactory.SetIntProperty(XMSC.WMQ_FAIL_IF_QUIESCE, 1);
connFactory.SetIntProperty(XMSC.WMQ_SHARE_CONV_ALLOWED, XMSC.WMQ_SHARE_CONV_ALLOWED_YES);
connFactory.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
We've tried
connFactory.SetStringProperty(XMSC.XMSC_WMQ_LOCAL_ADDRESS,"(45000,45010)");
We've also tried
connFactory.SetStringProperty(XMSC.XMSC_WMQ_LOCAL_ADDRESS,"localhost(45000,45010)");
We've also tried
connFactory.SetStringProperty(XMSC.XMSC_WMQ_LOCAL_ADDRESS,"192.168.12.156(45000,45010)");
End of tests and the rest below is as it was.
IDestination sendQ = xmsFactory.CreateQueue(string.Format("queue://{0}/{1}?targetClient=1", mqProfile.QueueManagerName, mqProfile.RequestQueue));
IDestination replyQ = xmsFactory.CreateQueue(string.Format("queue://{0}/{1}?targetClient=1", mqProfile.QueueManagerName, mqProfile.ReplyQueue));
var connContext = new XMSConnectionContext(connFactory.CreateConnection(), sendQ, replyQ, mqProfile, DateTime.Now.AddSeconds(qm.MqConfiguration.ConnectionPoolExpiryTime));
QueueManager.Log.DebugFormat("XMSConnectionContext-Instantiated: ProfileName={0} SendQ={1}, ReplyQ={2}, ConnectionMetaData={3}", connContext.ProfileName, connContext.SendQ, connContext.ReplyQ, connContext.Connection);
return connContext;
}
public void Close()
{
if (_connContext != null)
{
_connContext[Message.MessageId].Connection.Stop();
}
}
Any help would be appreciated. Thanks.
XMS .NET has a connection factory property, XMSC_WMQ_LOCAL_ADDRESS that lets you specify a local port to be used while connecting to a queue manager. More details here

Proxy does not accept offered credentials. C# remoting

I'm having trouble with a proxy server which won't accept the authentication details my application is offering it. Here is what I'm doing:
private bool DoLoginTest(WebProxy wp = null)
{
if(MMremotingClient.LoginWCP(wp) == AdminNetworkFlags.CLIENTPOS)
{
FL.Log("Test licensing server connection REM finished");
FL.Log("Connection could be established successfully");
MMremotingClient.DoTask(BitConverter.GetBytes((int)AdminNetworkFlags.CLIENTEND), "Nothing");
MMremotingClient.DisableFLogging();
Invoke(txtDelegate, " finished\r\n");
return true;
}
else
{
FL.Log("Test server connection failed!");
FL.Log("NoTask");
Invoke(txtDelegate, " failed\r\n");
Invoke(MBDelegate, "Could not reach the licencing server. Please make sure that no firewall is blocking port 80, or that your computer is allowed to access the internet.");
return false;
}
}
In a series of tests, i try to connect to a server with the old remoting protocol (upgrade to WCF not possible atm). If the DoLoginTest Method fails, the user will see a little form where he can enter the proxy details which get injected into the HTTPClientChannel object. Then another try to connect to the Server is made.
public static AdminNetworkFlags LoginWCP(WebProxy wProx = null)
{
FileLogger.Log("MMLC: LoginWCP");
Register(wProx);
return Login();
}
private static void Register(WebProxy iwp = null)
{
FileLogger.Log("MMLC: Register");
try
{
IDictionary props = new Hashtable();
if(iwp == null)
{
props["useDefaultCredentials"] = true;
}
else
{
NetworkCredential nc = (NetworkCredential)iwp.Credentials;
if(nc != null)
{
props["domain"] = nc.Domain ?? null;
props["password"] = nc.Password;
props["username"] = nc.UserName;
props["useDefaultCredentials"] = false;
}
else
{
props["domain"] = null;
props["password"] = "1234";
props["username"] = "u.name";
props["useDefaultCredentials"] = false;
}
}
ServicePointManager.Expect100Continue = false;
HttpChan = new HttpClientChannel(props, new BinaryClientFormatterSinkProvider());
SetChannelProxy(HttpChan, iwp ?? WebRequest.GetSystemWebProxy());
FileLogger.Log("MMLC: RegChannel");
ChannelServices.RegisterChannel(HttpChan, true);
RemoteObject = (IRemObject)Activator.GetObject(typeof(IRemObject), "http://someAdress:80/IRemObject");
FileLogger.Log("MMLC: connected");
}
catch(Exception x)
{
Trace.WriteLine("Error connecting to remote server, reason: " + x.Message);
RemoteObject = null;
}
}
private static void SetChannelProxy(HttpClientChannel channel, IWebProxy proxy)
{
FieldInfo proxyObjectFieldInfo = typeof(HttpClientChannel).GetField("_proxyObject", BindingFlags.Instance | BindingFlags.NonPublic);
proxyObjectFieldInfo.SetValue(channel, proxy);
}
This is the Form asking the user for Proxy details. If the User ends it with hitting the "OK" button on it, the defined Proxy property is set. That property is then passed to the LoginWCP() function.
private void button1_Click(object sender, EventArgs e)
{
definedProxy = new WebProxy(txtAdress.Text, decimal.ToInt32(nudPort.Value));
Address = txtAdress.Text;
Port = decimal.ToInt32(nudPort.Value);
NetworkCredential nc = new NetworkCredential()
{
Domain = string.IsNullOrWhiteSpace(txtDomain.Text) ? null : txtDomain.Text,
UserName = txtName.Text,
Password = txtPassword.Text
};
definedProxy.Credentials = nc;
DialogResult = System.Windows.Forms.DialogResult.OK;
Close();
}
So far this worked fine, but now I have the first user with an proxy in an Active Directory Environment. As i am lacking an AD, i cannot test the application in it. So I am asking you, is there anything wrong with my application? Do i need to check the user ipnut for something? is the Expect100Continue = falsedoing something bad?
So, this thing happened again, but this time it could be solved. First I have to name the culprit giving me a hard time. ZScaler. This software suite build around blocking and sniffing into connections from the outside and inside seems to only allow connections to adresses, and not direct IPs. Up to this point my application directly connected to an IP, instead of an real adress. Some Changes later, my server is now browsable by an address, and the application is let through by the proxy of the ZScaler.

How to use WMI commands to check if a system is connected to Internet? [duplicate]

This question already has answers here:
How do you determine if an Internet connection is available for your WinForms App?
(8 answers)
Closed 9 years ago.
In my winforms app i need to check if the system is connected to internet.
Currently I am using
try
{
Dns.GetHostEntry("www.something.com");
return true;
}
catch (Exception)
{
return false;
}
But this doesn't cut it for me. It takes more than two minutes to start the application if the system is not connected to internet(because of Timeout).
Was wondering if WMI command can be used instead?
I use This Class For Check Internet Connect
if User connect with Dsl Modem , below code Can't Sense Internet Connect
NetworkInterface.GetIsNetworkAvailable()
But This Class Can Solve This ,
class InternetConnectionChecker
{
private bool _connectingFlag = false;
private Thread _th;
#region Ping Google To Test Connect Or Disconnect
private string Ping()
{
try
{
const string remoteMachineNameOrIP = "173.194.78.104";
var ping = new Ping();
var reply = ping.Send(remoteMachineNameOrIP, 5);
var sb = new StringBuilder();
sb.Append(reply.Status.ToString());
return sb.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
#region Connecting Cheker Thread
private void ConCheck()
{
var status = Ping();
_connectingFlag = status == "Success" || status == "TimedOut";
}
public bool ConnectingCheker()
{
_th = new Thread(ConCheck);
_th.Start();
return _connectingFlag;
}
#endregion
}
For Use //Dont Forget Create Global Instance InternetConnectionChecker
InternetConnectionChecker _connectionChecker = new InternetConnectionChecker();
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
btn1.Content = _connectionChecker.ConnectingCheker();
}
I don't know about WMI, but there are some .NET Framework classes that can help in the System.Net.NetworkInformation namespace. In particular, NetworkInterface.GetIsNetworkAvailable() can tell you if a network connection (not necessarily with internet) is available. In the same namespace, the Ping class has several methods for send ping requests that are asynchronous and/or have timeout parameters.
I used wininet.dll instead to solve my problem and it works like a charm.
Please reference this link for its usage.
Thanks guys for your time.

Categories