Selenium Webdriver: How to confirm element no longer displayed on page - c#

I have a table containing details about jobs.
Currently I can use the following code to find the specified job and select delete.
[TestMethod]
public void DeleteJob()
{
JobsPage.GoTo();
JobsPage.Delete("TestJobTitle");
Assert.IsTrue(DeleteJobPage.IsAt, "Delete job page not displayed");
}
Below Method to find the specified job and click delete
public static void Delete(string delete)
{
var test = Driver.Instance.FindElement((By.XPath("//table/tbody/tr[td[2] = '" + delete + "']/td[9]/a[3]")));
test.Click();
}
I am now attempting to find a way to confirm the Job is no longer displayed on the JobsPage.
Assert.IsTrue(JobsPage._View("TestJobTitle"), "Job is still present");
The above Assert in the TestMethod is not working
I attempted the below method but need help to get working.
public static bool _View(string view)
{
IList<IWebElement> messages = Driver.Instance.FindElements(By.XPath("//table/tbody/tr[td[2] = '" + view + "']")).ToList();
foreach (IWebElement message in messages)
{
if (message.Text == view)
{
return true; // Job is still present
}
}
return false; // Job is not present
}

Don't know whether this helps or not. I have same scenario and I do search in a table for a user still exists or not.
public static bool ValidateSearchResult(string s)
{
bool val = false;
try
{
new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 0, 10)).Until(ExpectedConditions.ElementExists(By.TagName("tbody")));
IList<IWebElement> StatusColumnData = Drivers._driverInstance.FindElements(By.XPath("//table/tbody/tr/td[2]"));
foreach (IWebElement element in StatusColumnData)
{
if (element.Text.Contains(s))
{
val = true;
break;
}
else
val = false;
return val;
}
}
catch(Exception e)
{
throw (e);
}
}

Related

After refreshing the page, the selected filters is lost

In my web application, when I try to select some values for filtering data, it is going to be selected and saved in backend (C#) successfully, but after refreshing the page, the selected data is lost.
This is the code in Typescript, which being run after save button is clicked.
public async updateAndSaveLayout(isSavedForAllUsers: boolean): Promise<void> {
if (this.queryForm.valid) {
try {
this._modalReference.isLoaderVisible = true;
this.model.layout.query = {
q: [],
s: {}
}
this.model.layout.query = this.model.query;
let saved = null;
if (isSavedForAllUsers) {
saved = await this._tableLayoutService.addOrUpdateDefault(this.model.layout);
}
else {
saved = await this._tableLayoutService.addorUpdate(this.model.layout);
}
if (saved) {
this.submitData()
this._snackbarService.success('Saved successfully')
}
else {
this._snackbarService.error('Failed to save')
}
finally {
this._modalReference.isLoaderVisible = false;
}
}
}
Should I somehow call some code in ngOnInit function?

Foreach, With only one DisplayAlert Popup?

Hi guy's i'm trying to figure out a way to display a DisplayAlert Popup when Someone entered the Wrong details into the Login Process.
Issue is, The login's a little "Weird" I'm not comparing against a Database i'm comparing against a List of Customers I get from a APi So I have to loop threw to then find if the detail's are correct.
I have a login Phase 1() which Checks against the Wordpress API but I want to have this be able to notify on Phase 1 and 2, Phase 1 is a Username = Username Password = Password Where phase 2 is just a Username = Username , I know it's not secure The Login is more of a Formality then anything.
public async void Login_Phase1()
{
try
{
#region Login Phase 1
var client = new WordPressClient("http://XXX.co.za/wp-json/");
client.AuthMethod = AuthMethod.JWT;
try
{
await client.RequestJWToken(Usernamelabel.Text, Password.Text);
}
catch (Exception e)
{
await App.Current.MainPage.DisplayAlert("Something Went wrong", e.ToString(), "OK");
}
var x = client;
var isValidToken = await client.IsValidJWToken();
WpApiCredentials.token = client.GetToken();
if (isValidToken)
{
Login_Phase2();
}
else
{
await App.Current.MainPage.DisplayAlert("Detail's are Incorect", "Token not Found", "OK");
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
#endregion
}
public void Login_Phase2()
{
try
{
#region login Phase 2
var list = FetchCustomers.customers.ToList();
foreach (var user in list)
{
if (user.username == Usernamelabel.Text)
{
Preferences.Set("CId", user.id.ToString());
Preferences.Set("Token", WpApiCredentials.token);
Preferences.Set("CUsername", user.username);
Preferences.Set("CEmail", user.email);
Users.Loggedin = true;
Application.Current.SavePropertiesAsync();
App.Current.MainPage.DisplayAlert("Complete", "Login Process Complete, Enjoy", "OK");
App.Current.MainPage = new Home("Mica Market");
}
//Want to add a Display popup Here to say the information is entered incorrectly, but
not have it repeat 200 Time's
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
#endregion
}
Fetching all the Customers to check against
private async void ExtractWooData(List<Customer> x)
{
try
{
#region FetchC
RestAPI rest = new RestAPI("http://xxxxxx/wp-json/wc/v3/", "ck_a25xxxxxxxxxxx0", "cs_8xxxxxxxx8xxxx");
WCObject wc = new WCObject(rest);
int pageNum = 1;
var isNull = false;
List<Customer> oldlist;
while (!isNull)
{
var page = pageNum.ToString();
x = await wc.Customer.GetAll(new Dictionary<string, string>() {
{
"page", page
}, {
"per_page", "100"
}
});
oldlist = FetchCustomers.customers ?? new List<Customer>();
if (x.Count == 0)
{
break;
}
else
{
//1st loop customers needs to = 100
//2nd loop oldist needs to = 40+
//If count = 0 then => Combine Customers + Oldist
pageNum++;
FetchCustomers.customers = oldlist.Union(x).ToList();
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
#endregion
}
Any Advice?
you can replace the foreach with a LINQ query
// find the first match
var found = list.Where(user => user.username == Usernamelabel.Text).FirstOrDefault();
if (found != null)
{
// set preferences and navigation
}
else
{
// DisplayAlert
}

c# outlook addin userproperty of first item in collection not found

Outlook 2016
.Net Framework 4.5
i encounter a really strange behaviour:
when i iterate through the items collection of a contact folder in some very special undefined cases (which i do not really understand) some userproperties of the first item of the collection fail to load. However the UserProperties are definitly set.
The approach is following:
I open the contact folder (to which the items will be moved) in outlook.
then i execute the "test"
the execution of the test can be suammrized as following:
click button ->
start thread
iterate through the items (on first iteration no items are present).
add new items{
create item
set userproperty PRE before item is initially saved
save item
move item to desired folder
set userproperty POST after item is moved
save item
}
end thread
click button ->
start thread
iterate through the items (here the userproperty POST sometimes fails to load on the first item of the collection, however when i investigate it, it IS there. It only fails for the first item and succeeds for every other following item).
...END
it seems to me that outlook somehow fails to update the userproperty definitions timely. But note that the first BackgroundWorker thread is already finished when iterating through the items with the second backgroundworker thread.
The problem could be related to the fact that iam viewing the folder in the explorer while the items are added and iterated.
This bug is hard to reproduce and does only occur rarely.
however i'm really missing insight into the inner workings of outlook so i can only speculate.
Idea for workarounds:
I could add an item with all userproperties before moving it. the problem here is that i need to add new userproperties, after the item is initially saved and moved to the folder, in some scenarios.
in few cases the userproperty key is dynamically created (with a pattern) so it wouldn't be optimal to predefine all userproperties.
It's very important that the userProperties are reliably loaded because some important features are based upon them.
Does anybody has a clue how the problem is caused and how to solve it? because this behaviour is driving me crazy.
some Code (not the original but it should contain all the relevant aspects)
//Ribbon
TestNS.TestCaller testCaller;
string folderID = "00000000BDB409934ED327439481EB6E1E1CC4D3010055B62301B58E32478DCD8C0D3FA6304600002C4CA4400000";
public void testButton0_Action(Office.IRibbonControl control)
{
if(testCaller == null){
testCaller = new TestNS.TestCaller(ThisAddIn.Outlook,folderID);
}
testCaller.Run();
}
//Ribbon end
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
namespace TestNS
{
public class TestCaller{
private Outlook.Application application;
private BackgroundWorker worker = new BackgroundWorker();
private Test test = null;
private string folderId;
private bool init = true;
private bool busy = false;
public TestCaller(Outlook.Application application, string folderId){
this.application = application;
this.folderId = folderId;
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnCompleted);
}
public void Run()
{
if (!busy)
{
busy = true;
test = new Test(application, folderId, init);
worker.RunWorkerAsync();
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
test.Process();
test = null;
}
private void OnCompleted(object sender, RunWorkerCompletedEventArgs e)
{
busy = false;
init = false;
}
}
class Test
{
public const string key_preCreateProperty ="preCreate";
public const string key_postCreateProperty = "postCreate";
private Outlook.Application application;
private string folderId;
private bool createData;
public Test(Outlook.Application application,string folderId,bool createData)
{
this.application = application;
this.folderId = folderId;
this.createData = createData;
}
public void Process(){
Examine();
if(createData){
CreateData();
}
}
public void CreateData()
{
List<Poco> pocos = new List<Poco>();
for (int i = 0; i < 10; i++)
{
pocos.Add(
new Poco
{
Pre = "Pre" + i,
Post = "Post" + i
}
);
}
CreateContactItems(folderId,pocos);
}
public void Examine()
{
bool preIsLoaded = false;
bool postIsLoaded = false;
Debug.WriteLine(">>>Examine");
Outlook.MAPIFolder folder = application.Session.GetFolderFromID(folderId);
Outlook.Items folderItems = folder.Items;
int i = 0;
//print UserProperties registered to the items
foreach(Outlook.ContactItem contactItem in folderItems){
var itemUserProperties = contactItem.UserProperties;
string itemUserPropertiesString = "";
foreach (var itemProp in itemUserProperties)
{
Outlook.UserProperty prop = (Outlook.UserProperty)itemProp;
itemUserPropertiesString += " " +prop.Name + " " + prop.Value + " \n";
}
//HERE: sometimes it prints only Pre on the first index of the iteration
Debug.WriteLine(string.Format("i={0} , itemUserProperties Count={1} , following UserProperties: \n{2}", i++, itemUserProperties.Count, itemUserPropertiesString));
string pre = null;
string post = null;
try
{
pre = contactItem.GetUserProperty(key_preCreateProperty);
preIsLoaded = true;
}
catch(KeyNotFoundException ex){
Debug.WriteLine("Error: Pre Not found"); //should not happen - doesn't happen
}
try
{
post = contactItem.GetUserProperty(key_postCreateProperty);
postIsLoaded = true;
}
catch (KeyNotFoundException ex)
{
Debug.WriteLine("Error: Post Not found"); //shoul not happen - happens rarely totally indeterminitic
}
Marshal.ReleaseComObject(itemUserProperties);
}
Debug.WriteLine("<<<Examine");
if (folderItems.Count > 0 && (!preIsLoaded || !postIsLoaded))
{
MessageBox.Show("preIsLoaded="+preIsLoaded +" \n" +"postIsLoaded="+postIsLoaded);
}
Marshal.ReleaseComObject(folderItems);
Marshal.ReleaseComObject(folder);
}
public void CreateContactItems(string folderId,List<Poco> pocos)
{
Outlook.MAPIFolder folder = application.Session.GetFolderFromID(folderId);
foreach(Poco poco in pocos){
CreateContactItem(folder,poco);
}
Marshal.ReleaseComObject(folder);
}
public void CreateContactItem(Outlook.MAPIFolder testFolder,Poco data)
{
Outlook.ContactItem contactItem = application.CreateItem(Outlook.OlItemType.olContactItem);
contactItem.SetUserProperty(key_preCreateProperty, data.Pre);
contactItem.Save();
Outlook.ContactItem movedContactItem = (Outlook.ContactItem)contactItem.Move(testFolder);
Marshal.ReleaseComObject(contactItem);
contactItem = movedContactItem;
contactItem.FirstName = data.Pre;
contactItem.LastName = data.Post;
contactItem.SetUserProperty(key_postCreateProperty, data.Post);
contactItem.Save();
Marshal.ReleaseComObject(contactItem);
}
}
public static class Util
{
public static void SetUserProperty(this Outlook.ContactItem item, string name, dynamic value)
{
Outlook.UserProperty property = item.UserProperties[name];
if (property == null)
{
property = item.UserProperties.Add(name, Outlook.OlUserPropertyType.olText);
}
property.Value = value;
}
public static dynamic GetUserProperty(this Outlook.ContactItem item, string name)
{
Outlook.UserProperty property = item.UserProperties[name];
if (property != null)
{
return property.Value;
}
throw new KeyNotFoundException(string.Format("UserProperty name={0} not found", name));
}
}
public class Poco
{
public string Pre
{
get;
set;
}
public string Post
{
get;
set;
}
}
}
Thank you for any replies
Outlook Object Model cannot be used on a secondary thread within a COM addin. Outlook 2016 will raise an exception as soon as it detects an OOM object being accessed on a secondary thread.

Input string was not in a correct format in c#.Net for textbox for some of the table names

I have a text box to get the SQL statement from the users. So, the users can type the sql into the textbox and get the results.
private int hasData
{
get
{
try
{
string query = SqlStatement_tbx.Text;
int _hasData = GenericDataAccess.ExecuteScalar(query);
return _hasData;
}
catch (Exception ex)
{
Errorhandling.LogError(ex);
return -1;
}
}
}
In the above method, sometimes it works for some of the tables and sometimes not. I could not figure it out where am doing wrong.
If i do Select * from dba.condition it works.
If i do Select * from dba.project it reports Input String was not in a correct format.
Thanks
Update:
These are the codes in my code behind file
private int hasData
{
get
{
try
{
string query = SqlStatement_tbx.Text;
int _hasData = GenericDataAccess.ExecuteScalar(query);
return _hasData;
}
catch (Exception ex)
{
Errorhandling.LogError(ex);
return -1;
}
}
}
private string sqlStatement
{
get
{
return SqlStatement_tbx.Text;
}
}
protected void RunSql_btn_Click(object sender, EventArgs e)
{
CustomValidator cv = (CustomValidator)CustomValidator1;
cv.Validate();
if (cv.IsValid)
{
Panel1.Visible = false;
ExportData_btn.Visible = false;
EmptyData_pnl.Visible = false;
if (hasData > 0)
{
Panel1.Visible = true;
ExportData_btn.Visible = true;
BindGridView1();
}
else if (hasData == 0)
{
EmptyData_pnl.Visible = true;
}
else
{
GenericMethods.showPopup(AlertType.Information, "Please check your sql statement!");
}
}
}
protected void BindGridView1()
{
try
{
GridView1.selectStatement = sqlStatement;
GridView1.PagerStyle.HorizontalAlign = HorizontalAlign.Left;
GridView1.ExtDataBind();
}
catch (Exception ex)
{
Errorhandling.LogError(ex);
}
}
protected void ValidateInput(object source, ServerValidateEventArgs args)
{
try
{
string input = sqlStatement.Trim();
if (input.StartsWith("select", true, null))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
catch (Exception Ex)
{
Errorhandling.LogError(Ex);
}
}
ExecuteScalar
private static Object ExecuteScalar_returnObject_internal(string query, Object[] args)
{
using (SAConnection Conn = new SAConnection(GenerateConnectionString()))
{
SACommand Cmd = new SACommand(query, Conn);
foreach (Object o in args)
{
SAParameter p = Cmd.CreateParameter();
p.Value = o;
Cmd.Parameters.Add(p);
}
Conn.Open();
Object r = Cmd.ExecuteScalar();
Conn.Close();
Cmd.Dispose();
//SAConnection.ClearAllPools();
return r;
}
}
public static int ExecuteScalar(string query, params Object[] args)
{
return Convert.ToInt32(ExecuteScalar_returnObject_internal(query, args));
}
The error you are getting is being produced by the Convert.ToInt32 method in your GenericDataAccess.ExecuteScalar function. This means that the string (or whatever type it is) returned from ExecuteScalar_returnObject_internal is not a valid value that can be converted to an int.
Without seeing more of your code I cannot say for sure why it isn't returning the expected value, however I suggest you step through it with the debugger and evaluate the value being returned by ExecuteScalar_returnObject_internal. It should be fairly obvious why it cannot be converted to an int.
Update
Looking at more of your code we can see that the object being parsed is the result of Cmd.ExecuteScalar (i.e. SACommand.ExecuteScalar). Again, that's not part of the .Net framework but for the sake of speeding things up let's assume it uses SqlCommand.ExecuteScalar on the insides.
We can see that SqlCommand.ExecuteScalar has the following return value:
The first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty.
Returns a maximum of 2033 characters.
With that in mind, I would say that the first column of the first row when executing Select * from dba.project is either null (perhaps there are no results at all), or the value is not something that can be converted to an Int.
I recommend you debug your query to see what is the first row/column value, or add some error checking and do something else (such as display a message to say "no results found" or "Unexpected return type" or whatever you like)

Sharepoint Sequential Workflow not adding Task into Tasklist

After the deployment of the workflow onto the sharepoint site, I am able to start the workflow by creating new rows of a list. These are also reflected in the field, "no. of workflow in progress". However, I cannot seem to find the tasks created for specific users in the Task list.
As a beginner with Sharepoint development, I am not exactly sure what is wrong. Please kindly advise.
this is my tested code:
private void OnCreateTask_MethodInvoking(object sender, EventArgs e)
{
taskId1 = Guid.NewGuid();
// SPContentTypeId myContentTypeId=new SPContentTypeId("0x01080100e73fd5f172cb40d8a5dca97fad7a58b8");
SPContentType myContentType = SPContext.Current.Web.ContentTypes["Powerfull Approval Workflow Task"];
CreateTaskApproval_ContentTypeID = myContentType.Id.ToString();
#region Enable ContentTypes
if (this.workflowProperties.TaskList.ContentTypesEnabled != true)
{
workflowProperties.TaskList.ContentTypesEnabled = true;
}
bool contenTypeExists = false;
foreach (SPContentType contentType in workflowProperties.TaskList.ContentTypes)
{
if (contentType.Name == myContentType.Name)
{
contenTypeExists = true;
break;
}
}
if (contenTypeExists != true)
{
workflowProperties.TaskList.ContentTypes.Add(myContentType);
}
myContentType.EditFormUrl = "_layouts/SequentialWorkflow/TaskEdit/TaskEditForm.aspx";
myContentType.DisplayFormUrl = "_layouts/SequentialWorkflow/TaskEdit/TaskEditForm.aspx";
myContentType.Update();
#endregion
taskProperties.PercentComplete = (float)0.0;
taskProperties.AssignedTo = myInstantiationData.User;
taskProperties.DueDate = myInstantiationData.DueDate;
taskProperties.Description = myInstantiationData.Request;
taskProperties.StartDate = DateTime.Now;
taskProperties.Title = "Please approve " + this.workflowProperties.Item.DisplayName;
}

Categories