Windows Mobile Professional 6.1 how to test internet connection - c#

I have a WM 6.1 Prof. application that checks updates when user wishes to do so.
I want to check if there is any avaliable connection (GPRS or Wifi) before it attempts to connect to server.
I am also using openNETCF.NET dll here is what I have done but it doesn't work everytime,
also I am not sure which type of connection should I use and so.
Ok do you think is this good?
Thank you very much!
private static HttpWebRequest ConnectWeb(string urlx)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(urlx));
request.ContentType = #"application/octet-stream";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout(6000);
return request;
}
catch (Exception ex)
{
MessageBox.Show(Lang.CONNECTIONPROBLEM);
return null;
}
}
private bool downloadTest()
{
Stream stream;
HttpWebResponse response;
HttpWebRequest request = ConnectWeb(FileManager.url);
if (request!=null)
{
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
using (stream = response.GetResponseStream())
{
byte[] data = ReadFully(stream, (int)response.ContentLength);
writeByteArrayToFile(data, "data.zip");
}
}
response.Close();
stream.Close();
}
catch (Exception ex)
{
MessageBox.Show(Lang.CONNECTIONPROBLEM);
return false;
}
}

Don't disconnect your connection manager.
As soon as you use the Windows Mobile Connection Manager, a plug-in to the network stack (the Autobind Winsock Layered Service Provider) starts automatically binding your network connections to the network interface corresponding to the chosen destination. Basically, it forces the packets to go the right way. If you request a disconnection, it may not send them at all.
Instead you should call Connect before you try to connect to your update server, then RequestDisconnect once you're done with it. Use an Asynchronous connection and attach to the Connected event if you want it to work in the background.
To follow what IE does with choosing the correct destination - WiFi or GPRS - use ConnectionManager.MapUrl to determine the destination GUID, and pass that into Connect. The default mapping behaviour is:
If the server-name part of the URL has no dots, it's a Work address
If the server-name part appears in the list of Exceptions, it's a Work address
Otherwise, it's an Internet address
What it then does depends on how ActiveSync/Windows Mobile Device Center is set up, if the device is cradled, and what is selected under 'My network card connects to', for WiFi (Start > Settings > Connections tab > Network Cards or WiFi icon). If this is set to 'Work' and the mapping is 'The Internet' it will never use WiFi. If it's set to 'The Internet' it will use WiFi if that is associated and fall back to GPRS if not.
As I recall, .NET CF's HttpWebRequest will automatically make use of the Connection Manager, following IE's behaviour of mapping the destination, so you may not need the OpenNETCF class at all.

Related

How to open a localhost server accessible from all devices in C# Windows Forms

I'm building a C# (Windows Forms) application that should open a local server on the network. I've searched and googled thoroughly but it seems that nobody was exposed to the same problem that I have.
The code I'm posting below does indeed open up a localhost in the given port (when ran through VS or as a normal build), but the problem is, it's only accessible through my laptop. If I go to the IP address and port through my phone or any another laptop, it doesn't even find the server. After several tries and brainstorming. It seems to me that it doesn't really open up the server on the network per se. It just creates some sort of a virtual localhost accessible to and through the machine which ran the code only.
This is my code:
private HttpListener Listener = null;
//CHECK IF HTTP IS SUPPORTED
try
{
Listener = new HttpListener();
Listener.Prefixes.Add("http://localhost:3000/");
Listener.Start();
Listener.BeginGetContext(GetContextCallback, null);
}
catch {} //SUPPRESS THE EXCEPTION/ERROR
private void GetContextCallback(IAsyncResult ar)
{
// Get the context
var context = Listener.EndGetContext(ar);
// listen for the next request
Listener.BeginGetContext(GetContextCallback, null);
var responseString = string.Format("Hello, this is a template text");
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
// and send it
var response = context.Response;
response.ContentType = "text/html";
response.ContentLength64 = buffer.Length;
response.StatusCode = 200;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
I'm not unfamiliar with either the concept or C# itself. I've built several applications that do the same with Node.js and have built a handful of apps in C#. But this is my first try writing such an application in C#. What am I missing?

A connection attempt failed because the connected party did not properly respond... .NET Remoting

I have two apps on two computers. These apps are communicating by .NET Remoting.
First app acts as server for access to database, second app acts as client and writes that data to another database.
When my client calls some method on my remote object on server, I get following error:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond
192.168.200.60:31621
Well, that's nice, but I don't know anything about IP address 192.168.200.60, I was connecting to 172.XXX.XXX.216. It seems that there are two network connections and it's somehow not good for remoting.
ipcongif on my server look like that:
Exactly the same solution works on another 3 computers with Windows 2000, Windows XP and Windows 7. Server is developed in .NET Framework 2.0.
Client and server have common DLL library with two interfaces ICAOFactory and ICAO. First I create factory CAOFactory, which has method CreateCAO, which returns CAO object. When I call some method oh that ICAO object, it fails.
This is how my server app registers remoting object:
TcpChannel channel = new TcpChannel(31621);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(My_Server.CAOFactory), "My_Server", WellKnownObjectMode.Singleton);
This is how my client creates remote object:
My_Share.ICAOFactory srvFactory;
My_Share.ICAO srvCAO;
srvFactory = (My_Share.ICAOFactory)Activator.GetObject(typeof(Foerster_Share.ICAOFactory), "tcp://" + ip + ":" + port + "/My_Server");
srvCAO = srvFactory.CreateCAO(); // no problem
srvCAO.Init(dateTime); // problem
This is my CAOFactory object:
public class CAOFactory : MarshalByRefObject, ICAOFactory
{
public ICAO CreateCAO()
{
ICAO CAOObj = new CAO();
return CAOObj;
}
public void GetClientCount(out long clientCountSum, out long clientCountMax, out long clientCountActive)
{
clientCountSum = 0;
clientCountMax = 0;
clientCountActive = 0;
return;
}
public override object InitializeLifetimeService()
{
return null;
}
}
This is my CAO object:
public class CAO : MarshalByRefObject, ICAO
{
public void Ping()
{
return;
}
DateTime dtInit;
public void Init(DateTime dt)
{
dtInit = dt;
}
// + some other methods
}
Any help greatly appreciated!
What version of .NET are you targeting?
I think you need to use the bindTo property of the TcpChannel class https://msdn.microsoft.com/en-us/library/bb187434(v=vs.85).aspx to tell your server to bind to the correct NIC. This is probably most easily done in the configuration. Does your server project have an app.config? If not add one then add a section like this to it (this is copy/pasted from this question .Net Remoting: Indicate which local interface to use to connect to one server)
<configuration>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="0" bindTo="172.xxx.xxx.xxx" />
</channels>
</application>
</system.runtime.remoting>
</configuration>
This will tell the server to bind to the specific IP address.
Reordering network connection priority helped in my case.
http://ecross.mvps.org/howto/change-network-connection-priority-in-windows-10.htm
Press the Windows Key + X and select Network Connections from the menu.
Press the ALT key, click Advanced and then Advanced Settings.
Select the network connection and click the arrows to give priority to the network connection.
Click Ok when you are done organizing the priority of the network connection. The computer will now follow an order when connections are available.

Easy and reasonable secure way to identify a specific network

We like to enable some hidden features of our software only if it is run inside of the company network. The key requirements are:
no need for a third party library outside of DotNet 4.5.1
easy to implement (should not be more than some dozens of lines .. I don't want to reimplement a crypto library)
It should be reasonable safe:
at least: hard to reverse engineer
at best: "impossible" to break even with read-access to the source code
low maintenance overhead
Win2012-Server is available for installation of additional software (open source or own implementation prefered - server can be assumed to be safe)
What I have thought about:
Check if a specific PC is available with a known MAC or IP (current implementation, not really secure and some other flaws)
Test, if a service is available on a specific response (i.e. I send 'Hello' to MyServer:12345 - server responses with 'World')
Similar to 2nd but a more complex challenge (i.e. send a seed for a RNG to the server, verify the response)
Set up an apache with HTTPS and verify the certificate
If you use ActiveDirectory, you could add a reference to the System.DirectoryServices namespace and check
ActiveDirectorySite currentSite = ActiveDirectorySite.GetComputerSite();
then you can get a bit of information from the currentSite object and check against that. That's how I enable/disable features of an application I'm developing currently.
I also grab:
var client = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in client.AddressList)
{
if(ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipAddress = ip;
}
}
Which you can check to make sure the client is connected with the proper protocol.
I've choosen the last option: Set up a webserver in the intranet and verify the certificate.
It was easier than expected. There are enough tutorials for setting up an apache with https for every supported OS. The self-signed certificate have a lifetime of 9999 days - should be okay until 2042. The C#-part is also reasonable small:
private static bool m_isHomeLocation = false;
public static bool IsHomeLocation
{
get
{
if (m_isHomeLocation)
return true;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://yourLicenseServer:yourConfiguredPort");
request.ServerCertificateValidationCallback += ((s, certificate, chain, sslPolicyErrors) => true);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
var thumbprint = new X509Certificate2(request.ServicePoint.Certificate).Thumbprint;
m_isHomeLocation = (thumbprint == "WhateverThumbprintYourCertificateHave");
}
catch
{
// pass - maybe next time
}
return m_isHomeLocation;
}
}

How do I check the network connection win the fatest way?

I'm developing an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS.
I want to use a function which can check the network connection existence, I tried to use the code below but its too slow.
public static bool CheckForInternetConnection()
{
string url = "http://www.Microsoft.com/";
try
{
System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
System.Net.WebResponse myResponse = myRequest.GetResponse();
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
Any one have an idea for a faster way to do that. I mention that I'm working with VS2008 on win7
Since you're not doing anything with the content of the response, there's really no reason to request it, and wait for the network transfer of all that data. You might try setting myRequest.Method = "HEAD", which will just return headers (assuming the web server supports it), but obviously still verify that you can communicate with the remote web server.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.method.aspx
Assuming availability on your version of the .net runtime, you can call the static System.Net.NetworkInformation.GetIsNetworkAvailable() method. There are scenarios where that'll return true and you won't be able to route to the outside world, but it'll tell you whether your device has a network interface that's marked as being up.

How to check if a web service is up and running without using ping?

How can i check if a method in a web service is working fine or not ? I cannot use ping. I still want to check any kind of method being invoked from the web service by the client. I know it is difficult to generalize but there should be some way.
I use this method and it works fine :
public bool IsAddressAvailable(string address)
{
try
{
System.Net.WebClient client = new WebClient();
client.DownloadData(address);
return true;
}
catch
{
return false;
}
}
The only way to know if a web service method is working "fine" is to call the method and then to evaluate whether the result is "fine". If you want to keep a record of "fine" vs. time, then you can log the result of the evaluation.
There's no more general way to do this that makes any sense. Consider:
You could have code that creates an HTTP connection to the service endpoint, but success doesn't tell you whether the service will immediately throw an exception as soon as you send it any message.
You could connect and send it an invalid message, but that doesn't tell you much.
You could connect and send it a valid message, then check the result to ensure that it is valid. That will give you a pretty good idea that when a real client calls the service immediately afterwards, the real client should expect a valid result.
Unless the service takes that as an opportunity to crash, just to spite you!
The best technique would be to use WCF tracing (possibly with message-level tracing) to log what actually happens with the service, good or bad. A human can then look at the logs to see if they are "fine".
Powershell is by far an easy way to 'ping' a webservice endpoint.
Use the following expression:
Test-NetConnection -Port 4408 -ComputerName 192.168.134.1
Here is a failure response for a port that does not exist or is not listening;
WARNING: TCP connect to 192.168.134.1:4408 failed
ComputerName : 192.168.134.1
RemoteAddress : 192.168.134.1
RemotePort : 4408
InterfaceAlias : Ethernet0
SourceAddress : 192.168.134.1
PingSucceeded : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded : False
Here is a success result if the address/port is listening and accessible:
ComputerName : 192.168.134.1
RemoteAddress : 192.168.134.1
RemotePort : 4407
InterfaceAlias : Ethernet0
SourceAddress : 192.168.134.1
TcpTestSucceeded : True
just use try catch inside the method of your webservice and log exceptions to a log file or to the event log.
Example:
[OperationContract]
public bool isGUID(string input)
{
bool functionReturnValue = false;
try
{
Guid guid;
functionReturnValue = Guid.TryParse(input, guid);
}
catch (Exception ex)
{
Log.WriteServerErrorLog(ex);
}
return functionReturnValue;
}
You don't need to ping the webservice, but instead ping the server with a watchdog service or something. There is no need to "ping" the webservice. I also think you don't need to do this anyway.
Either your webservice works or it doesn't because of bad code.
You may try curl. It's a Linux tool, should be there in Cygwin too.
$ curl http://google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
here.
</BODY></HTML>
There are lots of options; examples can be found in the 'net.
You can write your self a little tool or windows service or whatever you need then look at these 2 articles:
C#: How to programmatically check a web service is up and running?
check to if web-service is up and running - efficiently
EDIT:
This was my implementation in a similar scenario where I need to know if an external service still exists every time before the call is made:
bool IsExternalServiceRunning
{
get
{
bool isRunning = false;
try
{
var endpoint = new ServiceClient();
var serviceUri = endpoint.Endpoint.Address.Uri;
var request = (HttpWebRequest)WebRequest.Create(serviceUri);
request.Timeout = 1000000;
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
isRunning = true;
}
#region
catch (Exception ex)
{
// Handle error
}
#endregion
return isRunning;
}
}
As I see it, you have 2 options:
If you can access the server it is running on, Log every call (and exceptions thrown). Read the log file with a soft like baretail that updates as the file is being written.
If you can't access the server, then you have to make the webservice write that log remotely to another computer you have access to.
Popular loggers have this functionality built in. (Log4Net, ...)
You could also use tracing.
http://msdn.microsoft.com/en-us/library/ms732023.aspx
http://msdn.microsoft.com/en-us/library/ms733025.aspx

Categories

Resources