validate sharepoint link in c# without using microsoft.sharepoint dll - c#

I am validating a regular URL as follows:
private static bool IsUrlAvailable(string url)
{
if ((string.IsNullOrEmpty(url.Trim()) == true) ||
(url.Trim().ToLower().Equals("http://")) ||
(url.Trim().ToLower().Equals("https://")))
{
return false;
}
if (!url.ToLower().StartsWith("http://") && !url.ToLower().StartsWith("https://"))
{
url = "http://" + url;
}
try
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 15000;
req.Method = "HEAD";
using (var rsp = (HttpWebResponse)req.GetResponse())
{
if (rsp.StatusCode == HttpStatusCode.OK)
{
return true;
}
}
}
catch (Exception ex)
{
// Eat it because all we want to do is return false
}
// Otherwise
return false;
}
But since I am using a WebRequest.Create, authenticated SharePoint urls on the intranet are failing validation because of permission denied (404) error. Now I know we can validate it using SPSite.Exists or OpenWeb but these are only available in microsoft.sharepoint.dll and I was wondering if there is a way of doing this without using this DLL?

404 is not permission denied... but file-not-found. So you may indeed hit non-existing Url.
You need to pass credentials with your request
WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Side note: please do not "eat all exceptions" - there is very small set of exceptions that are interesting in case of making WebRequests which you can find in article about HttpWebRequest.GetResponse (you likley should only handle WebException).

Related

Possible ways of WebRequest.Create("URL") always failed?

Currently in my website, I need to verify a URL param to ensure that it's a valid and it's an accessible URL. I'm using the code below:
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null) return false;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
I had deployed the website in my server and so far every work fine, no issue with the URL verification.
Now I had published the same application in client server. But the URL verification always failed even just for http://www.google.com. I have log file that record the failure of verification and the value.
I retrieve all those URL value in client site and test again in my own server but no issue at all.
That's why I suspect that it's not code issue but environment issue.
Any advice on what to check?
Thanks
Try the following. If there is an exception, hopefully it will give you a clue on the issue you are having.
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null) return false;
request.AllowRedirect = false; // default: true
request.Method = "GET"; // this is the default
try
{
var response = (HttpWebResponse)request.GetResponse());
if (res.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
}
catch (Exception ex)
{
return ex.Message;
}

how to know given website is https protected or not in C#

how to Verify where website is using https, a secure communication protocol/not.
like if i give www.facebook.com it should show https protected or not.im getting error in second line.im getting false even though site is https
checkSecured();
private void checkSecured()
{
string url = txturl.Text.Trim();
var uri = new Uri("https://www.facebook.com");
var requestType = uri.Scheme;
var value= HttpContext.Current.Request.IsSecureConnection;
}
there are many sites which works on both http and https, some works on http and some on https.
So in your url check twice
1) If http://+url is valid or not
2) if https://+url is valid or not.
Then you can get the result.
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
response.Close();
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
from: C# How can I check if a URL exists/is valid?
You can use the below line of code to check if the connection is secured or not.
HttpContext.Current.Request.IsSecureConnection

How to know if a website/domain is available before loading a webview with that URL

hello I am trying to launch an intent with a webview from a user entered URL, I have been looking everywhere online and I can't find a concrete answer as to how to make sure the website will actually connect before allowing the user to proceed to the next activity. I have found many tools to make sure the URL follows the correct format but none that actually let me make sure it can actually connect.
You can use WebClient and check if any exception is thrown:
using (var client = new HeadOnlyClient())
{
try
{
client.DownloadString("http://google.com");
}
catch (Exception ex)
{
// URL is not accessible.
}
}
You can catch more specific exceptions to make it more elegant.
You can also use custom modification to WebClient to check HEAD only and decrease the amount of data downloaded:
class HeadOnlyClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
req.Method = "HEAD";
return req;
}
}
I would suggest you to use HttpHead for simple request with AndroidHttpClient, but it is deprecated now. You can try to implement HEAD Request by sockets.
You can try to ping the address first.
See this SO question: How to Ping External IP from Java Android
Another option:
Connectivity Plugin for Xamarin and Windows
Task<bool> IsReachable(string host, int msTimeout = 5000);
But, any pre-check that succeeds isn't guaranteed as the very next request might fail so you should still handle that.
Here's what I ended up doing to Check if a Host name is reachable. I was connecting to a site with a self signed certificate so that's why I have the delegate in the ServiceCertificateValidationCallback.
private async Task<bool> CheckHostConnectionAsync (string serverName)
{
string Message = string.Empty;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serverName);
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true;
};
// Set the credentials to the current user account
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "GET";
request.Timeout = 1000 * 40;
try
{
using (HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync ())
{
// Do nothing; we're only testing to see if we can get the response
}
}
catch (WebException ex)
{
Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
return false;
}
if (Message.Length == 0)
{
goToMainActivity (serverName);
}
return true;
}

HttpWebRequest-The remote server returned an error: (400) Bad Request

I am getting The remote server returned an error: (400) Bad Request error while running the following code.
I am trying to upload xml file on the http server.
My xml file contains tag for the username,password and domain and when i am trying to connect is manually i am able to connect it,but using same credentials when i am trying to connect it through this code, i am getting 400 Bad Request error.
Please suggest me how to overcome this issue.
Thanks
`
public static void UploadHttp(string xml)
{
string txtResults = string.Empty;
try
{
string url = "http://my.server.com/upload.aspx ";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.KeepAlive = false;
request.SendChunked = true;
request.AllowAutoRedirect = true;
request.Method = "Post";
request.ContentType = "text/xml";
var encoder = new UTF8Encoding();
var data = encoder.GetBytes(xml);
request.ContentLength = data.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
WebResponse response = null;
response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var str = reader.ReadToEnd();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse err = ex.Response as HttpWebResponse;
if (err != null)
{
string htmlResponse = new StreamReader(err.GetResponseStream()).ReadToEnd();
txtResults = string.Format("{0} {1}", err.StatusDescription, htmlResponse);
}
}
else
{
}
}
catch (Exception ex)
{
txtResults = ex.ToString();
}
}`
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
400 Bad request Error will be thrown due to incorrect authentication entries.
Check if your API URL is correct or wrong. Don't append or prepend spaces.
Verify that your username and password are valid. Please check any spelling mistake(s) while entering.
Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.
What type of authentication do you use?
Send the credentials using the properties Ben said before and setup a cookie handler.
You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
//use "ASCII" or try with another encoding scheme instead of "UTF8".
using (StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.UTF8))
{
postStream.Write(postData);
postStream.Close();
}

How do you check if a website is online in C#?

I want my program in C# to check if a website is online prior to executing, how would I make my program ping the website and check for a response in C#?
A Ping only tells you the port is active, it does not tell you if it's really a web service there.
My suggestion is to perform a HTTP HEAD request against the URL
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("your url");
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
try {
response = request.GetResponse();
// do something with response.Headers to find out information about the request
} catch (WebException wex)
{
//set flag if there was a timeout or some other issues
}
This will not actually fetch the HTML page, but it will help you find out the minimum of what you need to know. Sorry if the code doesn't compile, this is just off the top of my head.
You have use System.Net.NetworkInformation.Ping see below.
var ping = new System.Net.NetworkInformation.Ping();
var result = ping.Send("www.google.com");
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
return;
Small remark for Digicoder's code and complete example of Ping method:
private bool Ping(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3000;
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
using (var response = request.GetResponse())
{
return true;
}
}
catch
{
return false;
}
}
if (!NetworkInterface.GetIsNetworkAvailable())
{
// Network does not available.
return;
}
Uri uri = new Uri("http://stackoverflow.com/any-uri");
Ping ping = new Ping();
PingReply pingReply = ping.Send(uri.Host);
if (pingReply.Status != IPStatus.Success)
{
// Website does not available.
return;
}
The simplest way I can think of is something like:
WebClient webClient = new WebClient();
byte[] result = webClient.DownloadData("http://site.com/x.html");
DownloadData will throw an exception if the website is not online.
There is probably a similar way to just ping the site, but it's unlikely that the difference will be noticeable unless you are checking many times a second.

Categories

Resources