I need to simulate a request to a page but I need to simulate it by code.
i'm using this code but not getting good results
private string RemoteURLChecking(string url)
{try{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
request.Timeout = 8000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (!response.ResponseUri.ToString().ToLower().Contains("pagenotfound"))
return "The page exists";
else
return "Page not Found";
}
catch (Exception ex)
{
return "Page not Found";
}
}
Thanks
You have a few choices, each of which has plenty of examples on MSDN:
Web Client
Web Browser Control
Related
I'm trying to access JSON on remote server. The code works on a local replica of the database but on the server there is a "HTTP Web Server: Command Not Handled Exception" error. I have lotusscript agents doing similar things so I am thinking it is a problem with java permissions on the server.
As far as I can tell I have all permissions on the server to run the code. I've tried putting the code in to Javascript and a Java managed bean so don't think it is an issue with the code.
The server is running 11.0.1FP1 (I've read there may be issues with pol files in 11)
Any help or hints would be greatly received
public String getJSON(String url)
{
String returnCode = url;
try {
String jsonTxt = null;
URL myURL = new URL(url);
HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection();
if (myURLConnection.getResponseCode() < 400) {
returnCode = "Connection made";
} else {
/* error from server */
jsonTxt = "Can not access remote server";
returnCode = "Connection not made";
}
myURLConnection.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
return returnCode;
}
I am getting Cross Site History Manipulation issue on a Checkmarx scan of my solution.
The issue I am getting is:
Method Page_Load at line 40 of xyz\abc.aspx.cs may leak server-side conditional values, enabling user tracking from another website. This may constitute a Privacy Violation.
THIS IS THE CODE AND I AM GETTING THE ERROR ON LINE (*)
protected void Page_Load(object sender, EventArgs e)
{
try
{
lblErrorMsg.Text = "";
lblErrorMsg.Visible = false;
if (!IsPostBack)
{
//Code to get the content page name.
string[] strPageInfo = HttpContext.Current.Request.ServerVariables.GetValues("PATH_INFO");
string strPage = strPageInfo[0].Substring(strPageInfo[0].LastIndexOf('/') + 1, ((strPageInfo[0].Length - strPageInfo[0].LastIndexOf("/")) - 1)).ToLower();
msg.MessageText = "Verifying access";
oLogger.LogInfo(msg, "Verifying access");
//firstly, check whether the logged-in user is authorized to view the page
ManageAuthorization.CheckAccess(strPage, out BoolAccess);
if (BoolAccess)
{
msg.MessageText = "Authorized to perform operations";
oLogger.LogInfo(msg, "Authorized to perform operations");
}
else
{
////display unauthorized screen
msg.MessageText = "Unauthorized to perform operations";
oLogger.LogWarning(msg, "Unauthorized to perform operations");
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
var byteArray = new byte[4];
var randomInteger = BitConverter.ToUInt32(byteArray, 0);
Response.Redirect(String.Format("../Default/Unauthorized.aspx?r={0}",randomInteger),true);
}
}
}
catch (Exception ex)
{
msg.MessageText = "Error while loading the page, Exception is:" + ex.Message;
oLogger.LogMessage(LogCategory.Error, msg);
}
}
I am not getting any proper answer how can I fix this, please can anybody help. Thanks in advance :)
Checkmarx is marking this as a vulnerability because a threat agent could potentially compromise the browser's SOP and may leak user information through activity inference.
To remediate this, you need to add a random value in your Redirects:
msg.MessageText = "Unauthorized to perform operations";
oLogger.LogWarning(msg, "Unauthorized to perform operations");
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
var byteArray = new byte[4];
provider.GetBytes(byteArray);
var randomInteger = BitConverter.ToUInt32(byteArray, 0);
Response.Redirect(String.Format("../Default/Unauthorized.aspx?r={0}", randomInteger), true);
I am tring to list all the management certificates in a windows azure subcription. And I tried with the following code. But it gives me an exception. And I could find that response is null and the exception message is "The remote server returned an error: (403) Forbidden."
Please help me with this. Msdn doesn't provide an example for this :(
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.Linq;
class ManagemenCertificateViewer
{
public static void Runme()
{
string msVersion = "2012-03-01";
string subscriptionId = "I used the subscription Id here";
try
{
ListManagementCertificates(subscriptionId, msVersion);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: ");
Console.WriteLine(ex.Message);
}
}
private static void ListManagementCertificates(string subscriptionId, string version)
{
string uriFormat = "https://management.core.windows.net/{0}/certificates";
Uri uri = new Uri(string.Format(uriFormat, subscriptionId));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers.Add("x-ms-version", version);
request.ContentType = "application/xml";
XDocument responseBody = null;
HttpStatusCode statusCode;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// GetResponse throws a WebException for 400 and 500 status codes
response = (HttpWebResponse)ex.Response;
}
statusCode = response.StatusCode;
if (response.ContentLength > 0)
{
using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
{
responseBody = XDocument.Load(reader);
}
}
response.Close();
if (statusCode.Equals(HttpStatusCode.OK))
{
XNamespace wa = "http://schemas.microsoft.com/windowsazure";
XElement storageServices = responseBody.Element(wa + "SubscriptionCertificates");
int mngmntCertificateCount = 0;
foreach (XElement storageService in storageServices.Elements(wa + "SubscriptionCertificate"))
{
string publicKey = storageService.Element(wa + "SubscriptionCertificatePublicKey").Value;
string thumbprint = storageService.Element(wa + "SubscriptionCertificateThumbprint").Value;
string certificateData = storageService.Element(wa + "SubscriptionCertificateData").Value;
string timeCreated = storageService.Element(wa + "TimeCreated").Value;
Console.WriteLine(
"Certificate[{0}]{1} SubscriptionCertificatePublicKey: {2}{1} SubscriptionCertificateThumbprint: {3}{1} certificateData{4}{1} timeCreated{5}{1}",
mngmntCertificateCount++, Environment.NewLine, publicKey, thumbprint, certificateData, timeCreated);
}
}
else
{
Console.WriteLine("List Management certificates returned an error:");
Console.WriteLine("Status Code: {0} ({1}):{2}{3}",
(int)statusCode, statusCode, Environment.NewLine,
responseBody.ToString(SaveOptions.OmitDuplicateNamespaces));
}
return;
}
}
Thanks it's working as I expected. I just add the following line and the Method 'GetCertificate(arg1)'
request.ClientCertificates.Add(GetCertificate(certThumbprint));
One more thing, in Msdn help guide there's a tag in respond body called
<TimeCreated>time-created</TimeCreated>
But the api responds not the TimeCreated its just created.
<Created> ..... </Created>
403 error means something wrong with your management certificate used to authenticate your Service Management API requests. I don't see you attaching a management certificate along with your request in your code. You may find this link useful for authenticating service management API requests: http://msdn.microsoft.com/en-us/library/windowsazure/ee460782.
HTH.
I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text
I have a webdav function listed below:
The behavior is completely unexpected....
When I first run the function and pass a URL to a resource (folder in sharepoint) that does not exist, I get a 404 which is expected. I then use another function to create the resource using THE SAME credentials as in this method. No problems yet...
However on 2nd run, after the resource has been created - when I check if resource exists, now I get a 401.
Whats important to note here is that the same credentials are used to check for 401 and create folder, so clearly the credentials are fine...
So it must be something else.... All I want to do is check if a resource exists in SharePoint.... any ideas how to improve this function? Or any theory as to why its giving this 401...
private bool MossResourceExists(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(this.Domain ))
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password , this.Domain )
);
}
else
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password )
);
}
request.Credentials = myCredentialCache;
try
{
request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Error checking if URL exists:" + url + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message ) ;
}
}
return true;
}
The only clue I have is that when using http://mysite.com/mydoclib/mytoplevelfolder it works.... any sub folders automatically give 401's....
The thing is that you can't pass the whole url that includes folders to the CredentialCache.Add() method.
For example:
http://MyHost/DocumentLibrary/folder1/folder2 will not work as an Uri to the Add() method, but
http://MyHost/DocumentLibrary/ will work.
I would guess that the lack of permissioning capabilities on folder level in SharePoint is the reason for this. Or the way that otherwise SharePoint handles folders.
What you can do is to separate the parameters in your method to accept a base url (including document libraries / lists) and a folder name parameter.
The CredentialCache gets the base url and the request object gets the full url.
Another way is to use the
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
credentials instead. And, if necessary, do an impersonation if you want to use another account than the executing one.
A third variation is to try with authentication type set to Kerberos instead of NTLM.
Here is my test code. I am able to reproduce the problem if I replace the problem with your code, and this code works for me.
static void Main(string[] args)
{
bool result = MossResourceExists("http://intranet/subtest/content_documents/", "testfolder/testfolder2");
}
private static bool MossResourceExists(string baseUrl, string folder)
{
string completeUrl = baseUrl + folder;
var request = (HttpWebRequest)WebRequest.Create(completeUrl);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(Domain))
{
myCredentialCache.Add(new Uri(baseUrl),
"NTLM",
new NetworkCredential(Username, Password, Domain)
);
}
else
{
myCredentialCache.Add(new Uri(baseUrl),
"NTLM",
new NetworkCredential(Username, Password)
);
}
request.Credentials = myCredentialCache;
//request.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
WebResponse response = request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Error checking if URL exists:" + completeUrl + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message);
}
}
return true;
}
Hope this helps.