DNS resolve failing for specific domains. Domains work with nslookup - c#

What I want to happen: Pass the method a domain as a string and have it return true if the domain resolves. False if it does not. The underlying goal is to see if a domain exists.
What happens: Most valid domain strings return true. Some, however, return false despite resolving with nslookup.
I don't understand why certain domains are failing to resolve when they look fine when using command prompt nslookup and nslookup sites. (I've used https://centralops.net/ , http://www.kloth.net/services/nslookup.php , and http://network-tools.com/nslook/)
Method (C#):
//no blank domains
public bool CheckDomain(string sDomain)
{
if (string.IsNullOrWhiteSpace(sDomain)) return false;
for (int i = 1; i <= mQueryRetry; i++)
{
try
{
System.Net.IPAddress dnsCli = System.Net.IPAddress.Parse("8.8.8.8")
DnsClient myClient = new DnsClient(dnsCli);
DnsMessage dnsMessage = myClient.Resolve(ARSoft.Tools.Net.DomainName.Parse(sDomain), RecordType.A);
if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
{
throw new Exception("DNS request failed");
}
else
{
foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords)
{
ARecord aRecord = dnsRecord as ARecord;
if (aRecord != null)
{
return true;
}
}
}
}
catch (Exception ex)
{
// Back off and try again after 1 seconds
if (i != mQueryRetry)
{
System.Threading.Thread.Sleep(1000);
}
else
{
System.Diagnostics.Trace.WriteLine(string.Format("Domain: {0} error: {1}", sDomain, ex.Message));
}
}
}
System.Diagnostics.Trace.Flush();
return false;
}
If you plan to test it, I suggest replacing the dnsCli IPAddress with one of these. I've left the IP for the google DNS server in there as an example but I am using my company's DNS server in my production code. I've found that changing the DNS server in no way impacts the method's behavior.
I am using the latest version of Arsoft.Tools.Net (2.2.8) for the DnsClient, DnsMessage, DomainName, DnsRecordBase, and ARecord, classes/objects. We had the same problem with an older version (1.8.1).
Some of the domains that are failing to resolve are:
appraisallinks-amc.com
resurgenstech.com
orpheusvr.com
trovvit.com
Additional info: I've tried some ludicrously long query timeout limits, upwards of 5 minutes, and they made no difference. Therefore, I am certain that this is not a timeout issue.

"you can try and use a different library, the DnsClient (nuget) instead, see dnsclient.michaco.net. The domain names in question seem to work just fine " -
#MichaC
The problem was in fact the Arsoft.Tools.Net library I was using. Switching to DnsClient.Net fixed the problem.

Related

DescribeTable Error Type, Amazon DynamoDB

I am referencing this answer to another, very similar question (the only difference being the use of PHP).
I have seen an example of getting detailed error information from an exception throw by AWS DynamoDB's DescribeTable method in PHP (see above linked answer); however, I have had trouble finding similar information in C#.
Here is what I have mimicked so far:
var describeTableResponse = _client.DescribeTable(tableName);
var responseStatusCode = describeTableResponse.HttpStatusCode;
if (responseStatusCode == HttpStatusCode.OK)
{
return true;
}
else if(responseStatusCode == HttpStatusCode.BadRequest)
{
var error = // get detailed information; looking for ResourceNotFoundException
}
throw new AmazonDynamoDBException("Error performing the DescribeTable operation");
Above, client is a correctly configured DB client of type AmazonDynamoDBClient.
Any thoughts on how to do the equivalent of:
$error_type = $response->body->__type;
$error_code = explode('#', $error_type)[1];
if($error_code == 'ResourceNotFoundException')
{
echo "Table ".$table_name." exists.";
}
I actually ended up going a completely different route due to the specification surrounding the .Net DescribeTable() function -- it throws the ResourceNotFoundException.
try
{
_client.DescribeTable(tableName);
}
catch (AmazonServiceException amazonServiceException)
{
if (amazonServiceException.GetType() != typeof(ResourceNotFoundException))
{
throw;
}
return false;
}
return true;

Check for internet connectivity from Unity

I have a Unity project which I build for Android and iOS platforms. I want to check for internet connectivity on Desktop, Android, and iOS devices. I've read about three different solutions:
Ping something (for example Google) - I totally dislike such decision, and I've read about mistakes on Android.
Application.internetReachability - According to Unity's documentation, this function will only determine that I have a POSSIBILITY of connecting to the Internet (it doesn't guarantee a real connection).
Network.TestConnection() - If I have no Internet connection, my application fails. So this isn't correct either.
How can I determine whether I have internet connectivity from within Unity?
I don't actually believe that Network.TestConnection() is the right tool for this job. According to the documentation, it looks to me like it's meant for testing if NAT is working and your client is publicly reachable by IP, but what you want to check for is whether you have general internet connectivity.
Here is a solution that I found on Unity Answers by user pixel_fiend, which simply tests a website to see if the user has connectivity. One benefit of this code is that it uses IEnumerator for asynchronous operation, so the connectivity test won't hold up the rest of your application:
IEnumerator checkInternetConnection(Action<bool> action){
WWW www = new WWW("http://google.com");
yield return www;
if (www.error != null) {
action (false);
} else {
action (true);
}
}
void Start(){
StartCoroutine(checkInternetConnection((isConnected)=>{
// handle connection status here
}));
}
You can change the website to whatever you want, or even modify the code to return success if any one of a number of sites are reachable. AFAIK there is no way to check for true internet connectivity without trying to connect to a specific site on the internet, so "pinging" one or more websites like this is likely to be your best bet at determining connectivity.
public static IEnumerator CheckInternetConnection(Action<bool> syncResult)
{
const string echoServer = "http://google.com";
bool result;
using (var request = UnityWebRequest.Head(echoServer))
{
request.timeout = 5;
yield return request.SendWebRequest();
result = !request.isNetworkError && !request.isHttpError && request.responseCode == 200;
}
syncResult(result);
}
void Start()
{
StartCoroutine(CheckInternetConnection(isConnected =>
{
if (isConnected)
{
Debug.Log("Internet Available!");
}
else
{
Debug.Log("Internet Not Available");
}
}));
}
IEnumerator CheckInternetConnection(Action<bool> action)
{
UnityWebRequest request = new UnityWebRequest("http://google.com");
yield return request.SendWebRequest();
if (request.error != null) {
Debug.Log ("Error");
action (false);
} else{
Debug.Log ("Success");
action (true);
}
}
Since WWW has deprecated, UnityWebRequest can be used instead.
i know this is old, but maybe can help you.
public bool CheckInternetConnection(){
return !(Application.internetReachability == NetworkReachability.NotReachable)
}
Ping 8.8.8.8 instead of sending a GET
unity already provides the tool for that:
Ping
The ping operation is asynchronous and a ping object can be polled for
status using Ping.isDone. When a response is received it is in
Ping.time.
Windows Store Apps: A stream socket is used to mimic ping
functionality, it will try to open a connection to specified IP
address using port 80. For this to work correctly, InternetClient
capability must be enabled in Package.appxmanifest.
Android: ICMP sockets are used for ping operation if they're
available, otherwise Unity spawns a child process /system/bin/ping for
ping operations. To check if ICMP sockets are available, you need to
read the contents for /proc/sys/net/ipv4/ping_group_range. If ICMP
sockets are available, this file should contain an entry for 0
2147483647.
using UnityEngine;
using System.Collections.Generic;
public class PingExample : MonoBehaviour
{
bool isConnected = false;
private IEnumerator Start()
{
while(true)
{
var ping = new Ping("8.8.8.8");
yield return new WaitForSeconds(1f);
while (!ping.isDone)
{
isConnected = false;
yield return null;
}
isConnected = true;
Debug.Log(ping.time);
}
}
}
I've created an Android's library that can be used as Unity's plugin for this purpose. If anyone's interested it's available under https://github.com/rixment/awu-plugin
As for the iOS version unfortunately I don't have enough of knowledge in this area. It would be nice if someone could extend the repo to include the iOS version too.
With the latest version of Unity, WWW has become obsolete, hence you need to use WebRequest.
This is the bit of codes I'm using to check if the user is online:
private string HtmlLookUpResult_Content;
private char[] HtmlLookUpResult_Chars;
private StreamReader HtmlLookUpResult_Reader;
private bool HtmlLookUpResult_isSuccess;
private HttpWebRequest HtmlLookUpResult_Request;
private HttpWebResponse HtmlLookUpResult_Response;
public bool CheckIfOnline()
{
HtmlLookUpResult_Content = UniversalEnum.String_Empty;
HtmlLookUpResult_Request = (HttpWebRequest)WebRequest.Create(UniversalEnum.WebHtml_isOnline);
HtmlLookUpResult_Request.Timeout = 5000;
try
{
using (HtmlLookUpResult_Response = (HttpWebResponse)HtmlLookUpResult_Request.GetResponse())
{
HtmlLookUpResult_isSuccess = (int)HtmlLookUpResult_Response.StatusCode < 299 && (int)HtmlLookUpResult_Response.StatusCode >= 200;
if (HtmlLookUpResult_isSuccess)
{
using (HtmlLookUpResult_Reader = new StreamReader(HtmlLookUpResult_Response.GetResponseStream()))
{
HtmlLookUpResult_Chars = new char[1];
HtmlLookUpResult_Reader.Read(HtmlLookUpResult_Chars, 0, 1);
HtmlLookUpResult_Content += HtmlLookUpResult_Chars[0];
}
}
}
}
catch
{
HtmlLookUpResult_Content = UniversalEnum.String_Empty;
}
if (HtmlLookUpResult_Content != UniversalEnum.String_Empty)
{
return true;
}
else
{
return false;
}
}
If you would like to know if the user is just online, you can get the result just from the boolean HtmlLookUpResult_isSuccess in the code. But, in reality, you most likely want to confirm the user has also access to your server or whatever remote system you use in your project, right? Which is what the remaining of the code does.
In case you wonder what UniversalEnum is, in my code, it's a separate non-Monobehavior script that contains all persistent variables (like strings and hashes) I'm planning on reusing in my project. For short:
UniversalEnum.String_Empty = "";
UniversalEnum.WebHtml_isOnline = "http://www.ENTER_YOUR_WEBSITE_HERE.com/games-latestnews/isOnline.html"
That isOnline.html file is, as you can see, a file in the folder "games-latestnews" in the HTML_content of my hosted website and it contains only [1] as it content. It has no header, no actual content and is pretty much like a .txt file set online. I'm using this method also because I can add new news to my game by just adding new HTML page in that folder. I'm also surrounding the content check with a Try{} so that if ANYTHING fails, it returns the Catch{} value and then by comparing if the content (a string) is an empty string or contain anything, we know if the user is both online and if he/she has access to your website.
On good example of why you would want to check that the user has both access to the net AND to your website is if the user is using a limited network such as what you might find at a school. If a school decided to ban your website due to whatever reason, just looking up if the connection is possible will return a false positive since it wouldn't access the actual webpage anyway.
You can check network connection using this code
if(Application.internetReachability == NetworkReachability.NotReachable){
Debug.Log("Error. Check internet connection!");
}

What is the correct way to TRY to Response.Redirect?

I want to redirect to a url, but be informed if it fails.
As far as I know a simple try-catch block won't work here because a Redirect always throws an exception. Although I can check for that exception (ThreadAbortException), but is this the best way?
EDIT: I'm trying to Redirect to a certain url, and if it doesn't exist - to another url.
Since redirect is client side operation (server simply sends response with code 302 and header location set to redirect destination) you can't expect server side Request.Redirect call to give you any indications if redirect succeeds on client (or even if it will be followed).
You options:
just live with that
if redirect is local you can at least verify if local path exists (or if ysing MVC - if route with given parameters is defined).
if redirect is remote you can try to issue request on the server first and see if response is reasonable (like "not 404").
Unfortunately all server side options to see if destination page exist have serious drawbacks:
checking for Url is potentially slow operation
you will not be albe to pass authentication information/cookes to pages on remote locations
some servers respond with 200 for "page really does not exist, look somewhere else".
I don't think this code will win a prize, but this at least prevents the ThreadAbortException...
Inspired by the KB article
bool redirectOK = false;
try
{
Repsonse.Redirect(url, false);
redirectOK = true;
}
catch(Exception exp)
{
// log/handle/whatever
}
if (redirectOK)
{
// do what even you want for a serverside succeeded redirect
}
else
{
// do what ever you want for a failure to redirect
}
Well, this will check for a 404 error, then direct to the page if there is no error.
if URLExists(theURL){
Response.Redirect(theUrl);
}
else{
//redirect somewhere else
}
public static bool UrlExists(string url)
{
try
{
if (url == "")
{
return false;
}
else
{
new System.Net.WebClient().DownloadData(url);
return true;
}
}
catch (System.Net.WebException e)
{
try
{
if (((System.Net.HttpWebResponse)e.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
return false;
else
throw;
}
catch
{
return false;
}
}
}

UCMA 3.0 How to build a list of recipients and then broadcast an IM call to those recipients

I am developing an application using UCMA 3.0 that will run as a service and send out periodic 'broadcasts' in the form of Instant Message calls. I have been using the book "Professional Unified Communications Development with Microsoft Lync Server 2010" and have everything provisioned fine and am able to establish an application endpoint.
I am stuck on two aspects though.
1) How to get a list of all users of Lync? Everything the UCMA can do is centered on a single user. For example it allows me to retrieve all contacts/groups present on a given users 'contact list' but does not provide any means to query for a list of available contacts that could be added to one of those contact lists. On the MSDN forum I found this post which leads me to think my best bet is simply to query AD directly.
2) What is the best way to actually send a broadcast style IM? My working premise is to attempt something like what I've found in this code example (specifically the public void SendIM() method).
So, get a list of recipients from AD, (looping on each on to check current presence?), and then use Automation to make the IM call for each recipient in the collection.
Does that make sense? Do I need to check presence of the recipient or do I just optimistically make the IM calls irregardless of their current presence status? Can anyone point me to some working code demonstrating sending an IM broadcast? You would think this is probably one of the most common use cases however the SDK samples do not cover it. Thanks in advance.
UPDATE:
As Lister says, there is no 'broadcast' method. I had to loop on the recipients and make a call to send an IM for each recipient. I found I also needed to check the recipients presence status as it would attempt to send messages to offline, busy, etc, users as well, resulting in exceptions. Figured best to only send to certain presence states. Since Application Endpoints do not have user/group lists you either need to determine recipients using AD and Directory Services or simply maintain your own list of recipients. I ended up writing a workflow where users can send an IM to the automaton application endpoint to opt-in or opt-out of alert broadcasts. The workflow maintains a simple subscriber database table.
/// <summary>
/// Sending of the actual IM to broadcast subscribers. Here we check that the presence of the target recipient
/// is in fact suitable for us to barge in with an alert.
/// </summary>
private void sendIMBroadcast(string sipTarget, byte[] htmlBytes)
{
try {
_appEndpoint.PresenceServices.BeginPresenceQuery(
new List<string>() {sipTarget},
new string[] {"state"},
null,
result =>
{
try
{
// Retrieve the results of the query.
IEnumerable<RemotePresentityNotification> notifications = _appEndpoint.PresenceServices.EndPresenceQuery(result);
// Grab the first notification in the results.
RemotePresentityNotification notification = notifications.FirstOrDefault();
if (notification == null)
{
logger.Warn("Invalid recipient for P1 broadcast: {0}", sipTarget);
return;
}
//ensure presense is one we want to send alert to
//if (notification.AggregatedPresenceState.AvailabilityValue )
long v = notification.AggregatedPresenceState.AvailabilityValue;
bool skip = false;
if (v >= 3000 && v <= 4499)
{
//online
}
else if (v >= 4500 && v <= 5999)
{
//idle online
}
else if (v >= 6000 && v <= 7499)
{
//busy
skip = true;
}
else if (v >= 7500 && v <= 8999)
{
//idle busy
skip = true;
}
else if (v >= 9000 && v <= 11999)
{
//dnd
skip = true;
}
else if (v >= 12000 && v <= 14999)
{
//brb
skip = true;
}
else if (v >= 15000 && v <= 17999)
{
//away
skip = true;
}
else if (v >= 18000)
{
//offline
skip = true;
}
if (skip == true)
{
logger.Debug("Skipping broadcast for user '{0}' due to presense status {1}.", sipTarget, v.ToString());
return;
}
logger.Debug("Sending broadcast for user '{0}' with presense status {1}.", sipTarget, v.ToString());
// Send an IM, create a new Conversation and make call
Conversation conversation = new Conversation(_appEndpoint);
InstantMessagingCall _imCall = new InstantMessagingCall(conversation);
try
{
ToastMessage toast = new ToastMessage("Unassigned P1 Tickets!");
// Establish the IM call.                 
_imCall.BeginEstablish(sipTarget,
toast,
new CallEstablishOptions(),
result2 =>
{
try
{
// Finish the asynchronous operation.
_imCall.EndEstablish(result2);
_imCall.Flow.BeginSendInstantMessage(
new System.Net.Mime.ContentType("text/html"),
htmlBytes,
ar =>
{
try
{
_imCall.Flow.EndSendInstantMessage(ar);
}
catch (RealTimeException rtex)
{
logger.Error("Failed sending P1 Broadcast Instant Message call.", rtex);
}
},
null
);
}
catch (RealTimeException rtex)
{
// Catch and log exceptions.
logger.Error("Failed establishing IM call", rtex);
}
},
null
);
}
catch (InvalidOperationException ioex)
{
logger.Error("Failed establishing IM call", ioex);
}
}
catch (RealTimeException ex)
{
logger.Error("Presence query failed.", ex);
}
},
null);
}
catch (InvalidOperationException ex)
{
logger.Error("Failed accepting call and querying presence.", ex);
}     
}
There really isn't a "broadcast IM" you pretty much get to iterate over your list of sip addresses you get from AD and do a BeginStartConversation on each Sip Address

Best way to handle a WCF timeout

I have a real time app that tracks assets around a number of sites across the country. As part of this solution I have 8 client apps that update a central server.
My question is that sometimes the apps lose connection to the central server and I am wondering what is the best way to deal with this ? I know I could just increase the max send/receive times to deal with the timeout BUT I also want a graceful solution to deal with if the connection to the server is down:
For example I'm calling my services like this :
using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
}
I was thinking of adding a try/catch so...
using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
try
{
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
}
catch (TimeoutException timeout)
{
LogMessage(timeout);
}
catch (CommunicationException comm)
{
LogMessage(comm);
}
}
Dealing it this way doesn't allow me to rerun the code without having a ton of code repeat. Any one got any suggestions ?
EDIT: Looking into Sixto Saez and user24601 answers having an overall solution is better than dealing with timeouts on an individual exception level BUT... I'm was thinking that the below would solve my problem (but it would add a TON of extra code error handling):
void Method(int statusId)
{
var statusRepository = new StatusRepositoryClient.StatusRepositoryClient()
try
{
IsServerUp();
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
statusRepository.Close();
}
catch (Exception ex)
{
statusRepository.Abort();
if (ex is TimeoutException || ex is CommunicationException)
{
LogMessage(timeout);
Method(statusId);
}
else
{
throw new Exception(ex.Message + ex.InnerException);
}
}
}
}
bool IsServerUp()
{
var x = new Ping();
var reply = x.Send(IPAddress.Parse("127.0.0.1"));
if (reply == null)
{
IsServerUp();
}
else
{
if (reply.Status != IPStatus.Success)
{
IsServerUp();
}
}
return true;
}
For starters I think your Wcf error handling is wrong. It should look like this
var statusRepository = new StatusRepositoryClient.StatusRepositoryClient();
try
{
statusId = statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
statusRepository.Close()
}
catch(Exception e)
{
statusRepository.Abort();
LogMessage(e);
throw; //I would do this to let user know.
}
I would also re-throw the error to let the user know about the problem.
Prior to designing your exception handling, one important decision to make is whether you want guaranteed delivery of each message the client sends or is it OK for the service to "lose" some. For guaranteed delivery, the best built-in solution is the netMsmqBinding assuming the client can be configured to support it. Otherwise, there is a lightweight reliable messaging capability built into WCF. You'll be going down a rabbit hole if you try to handle message delivery purely through exception handling... :)
I have a two-pronged approach to verifying the server is up:
1) I have set up a 'PING' to the server every 5 seconds. The server responds with a 'PONG' and a load rating (low, medium, high, so the client can adjust its load on the server). If the client EVER doesn't receive a pong it assumes the server is down (since this is very low stress on the server - just listen and respond).
2) Random timeouts like the one you are catching are logged in a ConnectionMonitor class along with all successful connections. A single one of these calls timing out is not enough to consider the server down since some may be very processor heavy, or may just take a very long time. However, a high enough percentage of these will cause the application to go into server timeout.
I also didn't want to throw up a message for every single connection timeout, because it was happening too frequently to people who use poorer servers (or just some computer lying in their lab as a server). Most of my calls can be missed once or twice, but missing 5 or 6 calls are clearly going to cause instrusion.
When a server-timeout state happens, I throw up a little dialog box explaining what's happening to the user.
Hi Please see my solution below. Also please note that the below code has not been compliled so may have some logic and typing errors.
bool IsServerUp()
{
var x = new Ping();
var reply = x.Send(IPAddress.Parse("127.0.0.1"));
if (reply == null) return false;
return reply.Status == IPStatus.Success ? true : false;
}
int? GetStatusId()
{
try
{
using (var statusRepository = new StatusRepositoryClient.StatusRepositoryClient())
{
return statusRepository.GetIdByName(licencePlateSeen.CameraId.ToString());
}
}catch(TimeoutException te)
{
//Log TimeOutException occured
return null;
}
}
void GetStatus()
{
try
{
TimeSpan sleepTime = new TimeSpan(0,0,5);
int maxRetries = 10;
while(!IsServerUp())
{
System.Threading.Thead.Sleep(sleepTime);
}
int? statusId = null;
int retryCount = 0;
while (!statusId.HasValue)
{
statusId = GetStatusId();
retryCount++;
if (retryCount > maxRetries)
throw new ApplicationException(String.Format("{0} Maximum Retries reached in order to get StatusId", maxRetries));
System.Threading.Thead.Sleep(sleepTime);
}
}catch(Exception ex)
{
//Log Exception Occured
}
}

Categories

Resources