I have 5 fields in a form which are pre populated. Using Selenium web driver how can I verify which one of the field is empty - selenium

I have a test case to verify a form. There are 5 fields which will be prepopulated. If any one of the field is empty, after submitting error message will come. I am fetching the text from all the fields and asserting if they are not null, asserting is failing since one field is null in these. But how to find out dynamically which field is empty.
There might be a possibility to take each field and assert each field if empty or not. but I guess that will make the code clumsy.
Any other ways by which I can do this?
Following is my code :
String sender = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$textsendername1")).Text;
String country = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlCountry")).Text;
String address1 = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtsenderaddress1")).Text;
String city = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtcity")).Text;
String state = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlstate")).Text;
String zip = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtzip")).Text;
try
{
Assert.IsNotEmpty(sender, country, address1, city, state, zip);
}
catch (Exception e)
{
String excep = e.ToString();
Console.WriteLine(excep);
}

I would create a function that determines if any of the fields are empty since you will likely be using this repeatedly.
public bool HasEmptyField()
{
string sender = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$textsendername1")).GetAttribute("value");
string country = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlCountry")).GetAttribute("value");
string address1 = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtsenderaddress1")).GetAttribute("value");
string city = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtcity")).GetAttribute("value");
string state = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$ddlstate")).GetAttribute("value");
string zip = driver.FindElement(By.Name("ctl00$ContentPlaceHolder$txtzip")).GetAttribute("value");
return string.IsNullOrEmpty(sender) ||
string.IsNullOrEmpty(country) ||
string.IsNullOrEmpty(address1) ||
string.IsNullOrEmpty(city) ||
string.IsNullOrEmpty(state) ||
string.IsNullOrEmpty(zip);
}
Your script would then look something like
bool expectError = HasEmptyField();
driver.FindElement(submitButtonLocator).Click(); // click submit button
if (expectError)
{
Assert.True(driver.FindElements(errorMessageLocator).Any(), "Verify error message exists");
// do something to address the error message
}
// continue the script

Related

SSRS/ASP.NET Setting all required report input parameters but still getting:One or more parameters required to run the report have not been specified

Although this has been asked before, none of the answers provided solve my issue. I AM passing in all of the required report parameters and all have HasValidValue set in the State property of the parameter array of ExecutionInfo. I am using ReportExecution2005.asmx in my ASP.NET web application. There is no GetParameters() call method to ReportExecution2005.ReportExecutionService object.
My report is calling a subreport so the input parameters are identical to the main report and the subreport. There are 4 single value inputs (two integer, two text) and then one Multivalue text input parameter which I supply multiple values for. I have double and tripled checked that the values I'm setting in the Multivalue input parameter match exactly one of the default parameters.
Here is the code that setups up the reports and renders/writes it out to a PDF file:
protected void btnPrintReq_Tests_Click(object sender, EventArgs e)
{
string query = string.Format("SELECT PatientFName, PatientLName, Address1 + ' ' + Address2 AS Address, City, Region AS State, PostalCode, Email, Phone, Gender, DOB, CONVERT(VARCHAR, ClinicID) AS ClinicID FROM Tbl_ShippingDropShip WHERE RequestID = {0}", giRequestID.ToString());
string sClinicID = string.Empty;
try
{
//get the drop ship test order details
SqlDataReader reader = default(SqlDataReader);
reader = o_cSQL.RunSQLReturnDataReader(query);
REService.ReportExecutionService rs_ext = new REService.ReportExecutionService();
rs_ext.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs_ext.Url = ConfigurationManager.AppSettings["ReportExecutionServer"];
List<string> ordereditems = new List<string> { };
ordereditems = GetOrderedItems(); //panels and profiles
int numordereditems = ordereditems.Count;
List<String> comments = new List<String>();
if (cbIce.Checked)
comments.Add("Ice");
if (cbKit.Checked)
comments.Add("Kit");
if (cbSwabs.Checked)
comments.Add("Swabs");
if (cbGoldTop.Checked)
comments.Add("Gold Top");
if (cbNeedlePack.Checked)
comments.Add("Needle Pack");
if (cbButterflyPack.Checked)
comments.Add("Butterfly Pack");
if (comments.Count == 0)
comments.Add("");
byte[] result = null;
string historyID = null;
string devInfo = null;
string encoding;
string mimeType;
string extension;
REService.Warning[] warnings = null;
string[] streamIDs = null;
//define the size of the parameter array to pass into the REService
REService.ParameterValue[] rValues = new REService.ParameterValue[4 + numordereditems];
while (reader.Read())
{
sClinicID = reader["ClinicID"].ToString();
rValues[0] = new REService.ParameterValue();
rValues[0].Name = "ClinicID";
rValues[0].Value = sClinicID;
rValues[1] = new REService.ParameterValue();
rValues[1].Name = "ReqFormID";
rValues[1].Value = giRequestID.ToString();
rValues[2] = new REService.ParameterValue();
rValues[2].Name = "DropShipID";
rValues[2].Value = giDropShipID.ToString();
rValues[3] = new REService.ParameterValue();
rValues[3].Name = "Comments";
rValues[3].Value = string.Join(",",comments.ToArray());
int j = 0;
for (int i = 4; i < rValues.Length; i++)
{
rValues[i] = new REService.ParameterValue();
rValues[i].Name = "PanelsNProfiles";
rValues[i].Label = "Panels and Profiles :";
rValues[i].Value = ordereditems[j++];
}
}
REService.ExecutionInfo res_info = new REService.ExecutionInfo();
res_info = rs_ext.LoadReport("/zReportSandbox/RequisitionDS", historyID);
res_info = rs_ext.SetExecutionParameters(rValues, "en-us");
res_info = rs_ext.GetExecutionInfo();
result = rs_ext.Render("PDF", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
string pdfFile = "Requisition_" + giRequestID.ToString() + "_"+ txtPatientName_Edit.Text + ".pdf";
string sPDFSavePath = ConfigurationManager.AppSettings["Shipping_Requisitions"] + sClinicID;
//add the date pathing
sPDFSavePath = ReportHelper.CreateDateDirectories(sPDFSavePath);
//make sure the file doesn't already exist and if it does, delete it so we create a new one
ReportHelper.checkPDFfilesNDirectory(sPDFSavePath +#"\", pdfFile);
FileStream stream = File.Create(sPDFSavePath + #"\" + pdfFile, result.Length);
stream.Write(result, 0, result.Length);
stream.Close();
}
catch(Exception ex)
{
Common.CommonUtilities.FatalError(sPageName, "btnPrintReq_Tests_Click", query, ex.Message.ToString(), ex.ToString());
}
}
I have noticed that the ExecutionInfo item shows me all parameters in the array of the report, meaning the required INPUT parameters AND the INTERNAL parameters, but also noticed that for the INTERNAL parameters, the default value that was set in the report is satisfied and ExecutionInfo shows them with the State of HasValidValue.
The following list is what I know
the report works on its own, so the Main report that calls the Subreport has no issues creating the PDF
there report when run in SSRS does prompt for the 4 input parameters
I have tried the removal of the report in SSRS and redeployed it because there were many that suggested this somehow fixes issues like this.
I have tried the Insert a table, delete the columns and put subreport in one cell of table trick and still the same error.
It would be nice if the error would state what parameter it sees as not being satisfied, even if there are more than one, then simply listing the first one before erroring out would help a developer work through the issues.
The attached picture shows the values I'm passing in for the multivalue parameters (PanelsNProfiles). I'm also attaching my RDL files for the main report and the Subreport, but had to add a (.txt) file extension to them to be able to upload them.
Here is the error in the SSRS execution log:
library!ReportServer_0-57!5250!03/23/2022-09:06:27:: i INFO: RenderForNewSession('/zReportSandbox/RequisitionDS')
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: , Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: One or more parameters required to run the report have not been specified.;
reportrendering!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: , Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS.;
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: An error has occurred while processing a sub-report. Details: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS. Stack trace:
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.FinalizeErrorMessageAndThrow()
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.RetrieveSubreport()

How to perform click on a string value?

I want to click a variable value which is stored in a string and below is my code.
OrderConfirmationData orderConfirmationData= (OrderConfirmationData)Serenity.sessionVariableCalled("OrderConfirmationData");
int maxtries=0;
System.out.println("Order is available in NTI" + EfloristConstants.lastname.get());
List<WebElement> recordcount = getDriver().findElements(By.xpath("//table[contains(#id,'ctrlDWController1_DWDetails1_gvNTI')]/*/tr[not(contains(#style,'bold'))]"));
int j=16;
for(int i=1;i<=recordcount.size();i++) {
j=j*i;
String record = "(//table[contains(#id,'ctrlDWController1_DWDetails1_gvNTI')]/*/tr[not(contains(#style,'bold'))]/td)["+j+"]";
String recipientname= element(By.xpath(record)).getTextValue();
if(recipientname.equals(orderConfirmationData.getShipFirstName() != null)) {
System.out.println("Order is available ");
}
j=16;
}
want to click on the recipientname when the, if the condition matches i.e want to perform click inside the If condition.
Add the below line in if condition:
element(By.xpath(record)).click()

jdbcTemplate query row map date column generically

I have a database with a date column, and when I perform a query I get each row as a Map of column names to column values. My problem is I do not know how to generically get the date column.
I am simply trying to cast it to a String at the moment, then parse it as java.util.Date, but this errors at the cast, and I am otherwise unsure as to how I can get the data?
This code is supposed to work with Sybase and Oracle databases too, so a generic answer would be greatly appreciated!
private static final String USER_QUERY = "SELECT USERNAME, PASSWORD, SUSPEND_START_DATE, SUSPEND_END_DATE FROM USERS";
public User readUsers(Subjects subjects) throws SubjectReaderException {
/* Perform the query */
List<User> users = new ArrayList<User>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(USER_QUERY);
/* Map the returned rows to our User objects */
for (Map<String, Object> row : rows) {
String username = (String) row.get("USERNAME");
/* Check if the user is suspended */
if(checkUserIsSuspended(row)){
continue;
}
User user = new User();
user.setUsername(username);
user.setPassword((String) row.get("PASSWORD"));
users.add(user);
}
return users;
}
private boolean checkUserIsSuspended(Map<String, Object> row) throws SubjectReaderException {
final String startDateString = (String) row.get("SUSPEND_START_DATE"); // this errors
if (startDateString != null) {
final String endDateString = (String) row.get("SUSPEND_END_DATE");
if (null != endDateString) {
return checkDate(startDateString, endDateString); // this just compares the current date etc
}
/* Return true if the Suspended start date is not null, and there is no end date column, or it is null */
return true;
}
/* Return false if the Suspended start date String is null - i.e. they have not been suspended */
return false;
}
The error:
java.lang.ClassCastException: com.sybase.jdbc3.tds.SybTimestamp cannot be cast to java.lang.String
It will always give this error because you are casting the Object com.sybase.jdbc3.tds.SybTimestamp to String.
Why don't you make this check directly in the SQL instead of creating a filter? Something like
SELECT USERNAME, PASSWORD, SUSPEND_START_DATE, SUSPEND_END_DATE
FROM USERS WHERE SUSPEND_START_DATE >= ?
and now you can use the queryForList passing as parameter the current time.
Another way for you to avoid this direct casts is using RowMapper. This way you can use ResultSet#getDate(String) and you won't be needing to cast anything as the JDBC driver will take care of the conversion for you :)

SharePoint 2010 - Custom calculated column

In a document library I need a custom calculated column, because the default Excel formula don't provide the functionality I need.
I created a custom field inheriting from SPFieldText, that I then could customize at will. The question is: how is it possible, from my custom field, to access the content values of the other fields of the document library?
In other world, in the overriden GetValidatedString method, how can I return a value that is dependent upon values from other fields, for the same record? How to implement getFieldValue() , below:
public class MyCustomField : SPFieldText
{
....
public override string GetValidatedString(object value)
{
string value1 = getFieldValue("Column-Name1");
string value2 = getFieldValue("Column-Name2");
return value1 + ", " + value2; // any arbitrary operation on field values
}
}
Thanks!
You should be able to grab other values from the form using the Item property of the FormComponent or the Item property of the ItemContext.
Either of these should work from the FieldControl class:
Code Snippet
if ((this.ControlMode == SPControlMode.New) || (this.ControlMode == SPControlMode.Edit))
{
object obj = this.Item["Name"];
if (obj != null)
string name = obj.ToString();
object obj2 = base.ItemContext.Item["Name"];
if (obj2 != null)
string name2 = obj2.ToString();
}
where "Name" is the internal name of the field that you wish to retrieve.

NHibernate: Add criteria if param not null

I'm trying to retrieve a list of orders based on parameters specified by a user (basic search functionality). The user will enter either an orderId or a bunch of other params, those will get wrapped up into a message, and eventually make their way to the method below. My question is, how do I only look at the parameters that actually have values? So if a user were to enter a received date range and a store number and all other fields were null, I want to return orders for stores received in the date range and ignore all the null parameters. At first I was thinking I could use a conjunction, but I can't see a way to ignore the null parameters. Then I started splitting things out into the if statements below the main expression, but I don't want to look at those criteria if the user provides an externalId. Is there a simple way to do this?
public IList<Core.Order> GetOrderByCriteria
(
string ExternalId,
int? Store,
int? Status,
DateTime? beforeTransmissionDate, DateTime? afterTransmissionDate,
DateTime? beforeAllocationProcessDate, DateTime? afterAllocationProcessDate,
DateTime? beforeReceivedDate, DateTime? afterReceivedDate
)
{
try
{
NHibernate.ICriteria criteria = NHibernateSession.CreateCriteria(typeof(Core.Order))
.Add(Expression.Or
(
Expression.Like("ExternalId", ExternalId),
Expression.Conjunction()
.Add(Expression.Between("ReceivedDate", beforeReceivedDate, afterReceivedDate))
.Add(Expression.Between("TransmissionDate", beforeTransmissionDate, afterTransmissionDate))
.Add(Expression.Between("AllocationProcessDate", beforeAllocationProcessDate, afterAllocationProcessDate))
)
);
if(Store.HasValue)
criteria.Add(Expression.Eq("Status", Status));
if(Status.HasValue)
criteria.Add(Expression.Eq("Store", Store));
return criteria.List<Core.Order>();
}
catch (NHibernate.HibernateException he)
{
DataAccessException dae = new DataAccessException("NHibernate Exception", he);
throw dae;
}
}
I wound up dropping the whole conjunction thing and replacing the code in the try block with the code below. I also used joins which reduced the number of db accesses and reduced the amount of code needed.
NHibernate.ICriteria criteria = NHibernateSession.CreateCriteria(typeof(Core.Order));
if (!String.IsNullOrEmpty(ExternalId))
{
criteria.Add(Expression.Like("ExternalId", ExternalId));
}
if (beforeReceivedDate != null && afterReceivedDate != null)
criteria.Add(Expression.Between("ReceivedDate", beforeReceivedDate, afterReceivedDate));
if (beforeTransmissionDate != null && afterTransmissionDate != null)
criteria.Add(Expression.Between("TransmissionDate", beforeTransmissionDate, afterTransmissionDate));
if (beforeAllocationProcessDate != null && afterAllocationProcessDate != null)
criteria.Add(Expression.Between("AllocationProcessDate", beforeAllocationProcessDate, afterAllocationProcessDate));
if (Store.HasValue)
criteria.CreateCriteria("Store", "Store").Add(Expression.Eq("Store.LocationNumber", Store.Value));
return criteria.List<Core.Order>();
I had to do something similar not long ago. I'm pretty sure you can modify this to fit your needs.
private ICriteria AddSearchCriteria(ICriteria criteria, string fieldName, string value)
{
if (string.IsNullOrEmpty(fieldName))
return criteria;
if(string.IsNullOrEmpty(value))
return criteria;
criteria.Add(Expression.Like(fieldName, "%" + value + "%"));
return criteria;
}
The code calling the method ended up looking like this:
var query = session.CreateCriteria(typeof (User));
AddSearchCriteria(query, "FirstName", form["FirstName"]);
AddSearchCriteria(query, "LastName", form["LastName"]);
var resultList = new List<User>();
query.List(resultList);
return resultList;
Leave it up to the function to determine if the input is valid and whether to return the unmodified ICriteria or to add another Expression before returning it.