How to validate a link showing 500 error in Selenium? - selenium

I am trying to validate the links of a website using server response code and page title, the server response found through the code shown below is 200 and page title is also same for all the pages.
the code is as follows:
if(url == null || url.isEmpty())
{
System.out.println("URL is either not configured for anchor tag or it is
empty");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else if(!url.startsWith(homePage)){
System.out.println("URL belongs to another domain, skipping it.");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else{
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode != 200){
System.out.println(url+" is a broken link");
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"broken_links",url);
}
else{
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
if (Actualtitle.contentEquals(unexpectedTitle)){
System.out.println(url+ " is a broken link");
objExcelFile.writeExcel(filePath,"broken_links",url);
} else {
System.out.println(url+ " is a valid link");
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"valid_links",url);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
The header is intact but the link is showing 500 error below the header. The issue is that even though page is showing 500 error, I am getting the server response code as 200, hence I am not able to make out whether this link is broken or not
This is the screenshot of the issue for the page I am validating :
enter image description here

Once you induce connect() as in :
huc.connect();
You can write as many for() loops to check any condition of the Response Code invoking getResponseCode() method as below :
if (huc.getResponseCode() == 200)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 500)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 404)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 402)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
System.out.println(
linkURL + " - " + huc.getResponseMessage() + " - " + huc.HTTP_NOT_FOUND);
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}

Related

Continue foreach loop even after an exception is encounterd in asp.net core razor pages

I have to log the exception into a database table and continue the foreach loop without any interruptions .
When i am trying to insert the exception into database table in catch block,its throwing null referenece exception. Here is my code.
foreach (var row in toEmailList)
{
foreach (var matrix in emailMatrixList.Where(u => names.Contains(u.BusinessUnit)))
{
// Send to Staff + Supervisor/Manager
if (row.DaysDueDate <= 42 && row.DaysDueDate >= 28)
{
if (matrix.StaffID.Equals(row.StaffID))
{
if (!row.EmailLevelSent.Equals("First Level"))
{
try {
var message = new MailMessage();
var bodyText = "<div style='font-family: Calibri, Arial, Helvetica, sans-serif;'>" +
"<p>Dear #FirstName #LastName,</p>" +
"<p>This is a notification to remind you that you have <b>#DaysDueDate</b> days to complete the following online <b>#TrainingTitle</b> training.</p>" +
"<p>Please remember to complete the training course within the next few days.</p>" +
"<p>If you do not complete this training within the required time frame, this information will be forwarded to your next level manager.</p>" +
"<p>Thank you very much,<br/>Kind regards,</p>" +
"<p>Manager</p>" +
"</div>";
var body = bodyText.Replace("#FirstName", row.FirstName).Replace("#LastName", row.LastName).Replace("#DaysDueDate", row.DaysDueDate.ToString()).Replace("#TrainingTitle", row.TrainingTitle.ToString());
if (matrix.StaffEmail.Contains("#domain.com"))
{
message.To.Add(new MailAddress(row.StaffEmail));
}
else if (matrix.ManagerEmail.Contains("#domain.com"))
{
message.To.Add(new MailAddress(matrix.ManagerEmail));
}
message.From = new MailAddress(_from);
message.Subject = "Training Notification for " + row.TrainingTitle;
if (matrix.ManagerEmail.Contains("#domain.com"))
{
message.CC.Add(new MailAddress(matrix.ManagerEmail));
}
else if ((matrix.ManagerEmail.Contains("N/A")) || (matrix.ManagerEmail.Contains("NA")) || (matrix.ManagerEmail.Contains("#N/A")) || (matrix.ManagerEmail.Contains("na")))
{
message.To.Add(new MailAddress(row.StaffEmail));
}
if (!string.IsNullOrEmpty(matrix.InTheLoop))
{
message.CC.Add(new MailAddress(matrix.InTheLoop));
}
message.Body = string.Format(body);
message.IsBodyHtml = true;
await smtp.SendMailAsync(message);
TempData["MailSent"] = "MailSent";
Debug.WriteLine("Sending first level email to " + row.FirstName + " " + row.LastName);
Debug.WriteLine("CC: " + message.CC.ToString());
row.EmailLevelSent = "First Level";
Debug.WriteLine("First Level email sent to " + row.FirstName);
}
catch (Exception e)
{
FailedEmails.StaffID = row.StaffID;
FailedEmails.FirstName = row.FirstName;
FailedEmails.LastName = row.LastName;
FailedEmails.StaffEmail = row.StaffEmail;
FailedEmails.ExceptionLog = e.Message;
FailedEmails.SentDate = DateTime.Now;
_context.Entry(FailedEmails).State = EntityState.Added;
}
}
}
}
}
}
Any help would be appreciated, is there anything i am missing. Thanks!

Searching for string in SQL table (Visual Studio C#)

I am banging my head against the wall with this. I am trying to create a search function for a table in my database. I want to be able to search by ID and by first name + last name.
The search by ID function is working perfect:
if (is_id_search)
{
for (int i = 0; i < rowcount; i++)
{
if (table.Rows[i][0].ToString() == searched_id)
{
MessageBox.Show("Student With ID: " + searched_id + " Found", "", MessageBoxButtons.OK);
display_searched_info(table.Rows[i]);
break;
}
else
{
if (i == (rowcount - 1))
{
MessageBox.Show("SEARCH FAILED: Student ID Not Found!", "Search Failed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
But when I try the same with searching by name it can't match the input string and the value in the table, I have even set a MessageBox to pop up on each iteration of the for loop displaying row[i][column].ToString() and it outputs the name I am searching but still says not found (code below):
else
{
for (int i = 0; i < rowcount; i++)
{
MessageBox.Show(table.Rows[i][1].ToString());
if (table.Rows[i][1].ToString() == searched_Fname)
{
MessageBox.Show("Student By Name Of: " + searched_Fname + " Found!", "Success!", MessageBoxButtons.OK);
break;
}
else
{
if (i == (rowcount - 1))
{
MessageBox.Show("Student By The Name Of: " + searched_Fname + " " + searched_Lname + " Not Found",
"Search Failed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Any help/advice is greatly appreciated (a couple of screenshots below)
output string from searched column
error message
Have you tried changing (table.Rows[i][0].ToString() == searched_Fname) for the String

Getting "object reference not set to an instance" in HttpContext.Current.Application

I'm hardly to figure out how to solve this.. I want to catch the error when the server is turn off and redirect the page to Maintenance.aspx. But it's getting error at HttpContext.Current.Application["ErrorCode"].ToString();.Please help me how to solve this...
Many thanks.
try{
// method here
}
catch (Exception ex)
{
Panel1.Visible = true;
string statuscode = HttpContext.Current.Application["ErrorCode"].ToString(); //Getting error here!
if (statuscode != null || statuscode != string.Empty)
{
if (statuscode == "500")
{
lblDetailMsg.Text = "<b>Error Page- <b> " + HttpContext.Current.Application["ErrorPage"].ToString() + " <br /> <b>Error Message-</b> The Requested Page was not found.";
Response.Redirect("Maintenance.aspx");
}
}
}
If I understand your code right, then the error must be due to .toString() method.
Try this
string statuscode = Convert.ToString(HttpContext.Current.Application["ErrorCode"]); // added Convert.Tostring()
if (statuscode != null || statuscode != string.Empty)
{
if (statuscode == "500")
{
lblDetailMsg.Text = "<b>Error Page- <b> " + Convert.ToString(HttpContext.Current.Application["ErrorPage"]) + " <br /> <b>Error Message-</b> The Requested Page was not found.";
Response.Redirect("Maintenance.aspx");
}
}
Convert.ToString() handles null, while ToString() doesn't.
Here it seems that HttpContext.Current.Application["ErrorCode"] does not contain value for "Error Code", so it giving null value.

How to disable/deactivate a SalesForce User through SOAP API?

I want to disable a User programmetically by using SOAP API. How can I do that? I am using Partner API and I have Developer edition. I have manage users persmissions set. I have gone through this link. I am looking for code which can help me disable/deactivate a User.
This is my code:
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class DeactivateUser {
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername("waprau#waprau.com");
config.setPassword("sjjhggrhgfhgffjdgj");
PartnerConnection connection = null;
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Username, IsActive from User");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
if(s.getField("Username").equals("abcd#pqrs.com")){
System.out.println("Username: " + s.getField("Username"));
s.setField("IsActive", false);
}
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}
This is output:
Username: waprau#waprau.com IsActive: true
Username: jsmith#ymail.net IsActive: false
Username: abcd#pqrs.com
Username: abcd#pqrs.com IsActive: false
However in UI when I go to My Name > Setup > Manage Users > Users, it always show 'Active' check box for user abcd#pqrs.com selected :-(
It doesn't look like you're actually sending the update back to Salesforce - you're just setting IsActive to false locally. You will need to use a call to PartnerConnection.update(SObject[] sObjects) in order for Salesforce to reflect your changes, like so:
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Id, Username, IsActive from User");
if ( queryResults.getSize() > 0 ) {
// keep track of which records you want to update with an ArrayList
ArrayList<SObject> updateObjects = new ArrayList<SObject>();
for (SObject s : queryResults.getRecords()) {
if ( s.getField("Username").equals("abcd#pqrs.com") ){
System.out.println("Username: " + s.getField("Username"));
s.setField("Id", null);
s.setField("IsActive", false);
}
updateObjects.add(s); // if you want to update all records...if not, put this in a conditional statement
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
// make the update call to Salesforce and then process the SaveResults returned
SaveResult[] saveResults = connection.update(updateObjects.toArray(new SObject[updateObjects.size()]));
for ( int i = 0; i < saveResults.length; i++ ) {
if ( saveResults[i].isSuccess() )
System.out.println("record " + saveResults[i].getId() + " was updated successfully");
else {
// There were errors during the update call, so loop through and print them out
System.out.println("record " + saveResults[i].getId() + " failed to save");
for ( int j = 0; j < saveResults[i].getErrors().length; j++ ) {
Error err = saveResults[i].getErrors()[j];
System.out.println("error code: " + err.getStatusCode().toString());
System.out.println("error message: " + err.getMessage());
}
}
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
It is possible to directly work with the user record without the SOQL query if you already know the Id.
SalesforceSession session = ...;
sObject userSObject = new sObject();
userSObject.Id = "00570000001V9NA";
userSObject.type = "User";
userSObject.Any = new System.Xml.XmlElement[1];
XmlDocument xmlDocument = new XmlDocument();
XmlElement fieldXmlElement = xmlDocument.CreateElement("IsActive");
fieldXmlElement.InnerText = bool.FalseString;
userSObject.Any[0] = fieldXmlElement;
SaveResult[] result = session.Binding.update(new sObject[] { userSObject });
foreach(SaveResult sr in result)
{
System.Diagnostics.Debug.WriteLine(sr.success + " " + sr.id);
if(!sr.success)
{
foreach(Error error in sr.errors)
{
System.Diagnostics.Debug.WriteLine(error.statusCode + " " + error.message);
}
}
}

IPathVariableManager.validateValue(URI) returns null

in the Eclipse plugin I'm working on I have a piece of code which basically looks like this:
public static void checkProblemV1() {
try {
String path = "C:\\temp";
org.eclipse.core.runtime.IPath value =
new org.eclipse.core.runtime.Path(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV1(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV1(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setValue(name, value); // setValue is deprecated
System.out.println("checkProblemV1(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV1(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV1(): statusValue is not OK.");
}
}
}
catch (CoreException e) {
System.err.println("checkProblemV1(): CoreException: " + e.getMessage());
}
}
When the above method is executed, there are no problems, but I get a deprecation warning for setValue() when compiling. It's when I wanted to fix that deprecation warning by replacing the call to setValue() with a call to setURIValue() that I got into trouble. First I had to tweak how that Windows-style path was written to avoid an URISyntaxException but after doing that, setURIValue() returns null and after having a look in the documentation I can't see that it should do that? I guess the URI is invalid after all but don't know how to fix it. Below is a test method in the same style as the one above demonstrating the problem.
public static void checkProblemV2() {
try {
String path = "C:\\temp";
// Have to replace \ with /, or we get URISyntaxExeption:
// checkProblemV2(): URISyntaxException: Illegal character in opaque part at index 2: C:\temp
path = path.replace('\\', '/');
java.net.URI value = new java.net.URI(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV2(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV2(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setURIValue(name, value);
System.out.println("checkProblemV2(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV2(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV2(): statusValue is not OK.");
}
}
}
catch (URISyntaxException e) {
System.err.println("checkProblemV2(): URISyntaxException: " + e.getMessage());
}
catch (CoreException e) {
System.err.println("checkProblemV2(): CoreException: " + e.getMessage());
}
}
When I run the above two methods, I get the following output.
checkProblemV1(): Everything fine
checkProblemV2(): statusName is not null: 'Status OK: unknown code=0 OK null'.
checkProblemV2(): statusValue is null
Thanks for reading and for any help, it's seriously appreciated!
There's a bug in org.eclipse.core.internal.resources.PathVariableManager.validateValue(URI) where it is using other internal methods but returning null no matter what else is going on. Please open a bug with Eclipse Platform/Resources.
And I agree with your comment, you should use:
URI uri = new File("C:\\temp").toURI();
pathManager.setURIValue(theName, uri);