I am using a WebDialogResult defined on a SmartPanel by calling AskExt() that is used to prompt for a password.
Unfortunately, it caches the password that's entered, so it keeps pre-filling the dialog and I want it to be blank every time the dialog is called.
I've tried a variety of different things, such as calling with .AskExt(true), which is supposed to refresh the dialog and invoked .ClearDialog() before calling .AskExt(), and numerous other things including .Cache.Clear(), .Cache.ClearQueryCache(), .Reset(), .Update(new PwdFields()), .Delete(.Current) as well as the more direct .Current.Pwd = null and .Current.Pwd = "", but nothing works.
That is browser problem. In order to solve it I propose you to find id of control with help of firefox or chrome developer toolbar, and use javascript which will clean values.
Then you can add jquery like this:
$( document ).ready(function() {
$("#ctl00_phG_PXSPanelVerify2_PXFormViewVerify2_CustEdPwd2").focus()
{
$("#ctl00_phG_PXSPanelVerify2_PXFormViewVerify2_CustEdPwd2").text("");
}
});
Eventually the combination below consistently cleared the dialog of the password whenever it was re-displayed.
if (this.PasswordLookup1Status.AskExt(true) == WebDialogResult.OK)
{
string currentPassword = this.PasswordLookup1Filter.Current.Pwd;
this.PasswordLookup1Filter.Current.Pwd = "";
this.PasswordLookup1Filter.Update(this.PasswordLookup1Filter.Current);
if (currentPassword == "1234")
{
Base.Transactions.Ask("Information", "Password [" + currentPassword + "] is correct.", MessageButtons.OK);
Base.Transactions.ClearDialog();
}
else
{
throw new PXException("Password [" + currentPassword + "] is incorrect.");
}
this.PasswordLookup1Filter.ClearDialog();
}
Related
I am using Firesharp for my app in c# winforms. This database is also connected to my ReactJS website which deals with the same information.
I have noticed that when I make .SetAsync calls to my app on the website and then log in to my Winforms app, my WinForms app will automatically perform the last action I did on my website to my database which is a .setAsync() action which adds some user information to a list of other user's information. Now it will not stop. Anytime I log on to my c# app, it runs it.
It makes me think there is a queue of orders in firesharp?
here is my react code. From what I can tell, it is nothing out of the ordinary:
async function handleSubmit(e) {
e.preventDefault()
var date = moment().format("MM/DD/YYYY" )
setError("")
setLoading(true)
// grab user info first then use that.
await firebaseApp.database().ref("Users/" + currentUser.uid + "/UserData").on('value', snapshot => {
if (snapshot.val() != null) {
setContactObjects({
...snapshot.val()
})
firebaseApp.database().ref("Projects/" + projectGUIDRef.current.value + "/queueList/" + userIdRef.current.value).set({
"EntryTimeStamp": date + " " + moment().format("hh:mm:ss a"),
"IsSyncing": false,
"UserId": userIdRef.current.value,
"UserName": usernameRef.current.value,
})
}
})
history.push("/Demo")
setLoading(false)
}
here is my c# winforms code of where the code is executing. For some reason, when this executes, it also updates the EntryTimeStamp field of the react code and completely sets all the information even if I delete it. It also happens if I run .set().
updateLastLogin2(authLink);
private async void updateLastLogin2(FirebaseAuthLink authLink)
{
IFirebaseConfig config = new FireSharp.Config.FirebaseConfig
{
AuthSecret = this.authLink.FirebaseToken,
BasePath = Command.dbURL,
};
IFirebaseClient client = new FireSharp.FirebaseClient(config);
string newDateTime = DateTime.Now.ToString();
if (authLink.User.DisplayName.Contains(adUserId) && authLink.User.DisplayName.Contains(adUserId))
{
await client.SetAsync("Users/" + this.authLink.User.LocalId + "/UserData/DateLastLogin", newDateTime);
}
}
Any and all help is appreciated, I've been at this for a day and a half now.
I have never used fire-sharp but this is my guess
You are calling await firebaseApp.database().ref("Users/" + currentUser.uid + "/UserData").on('value' in your react, and then in your Csharp you are calling client.SetAsync("Users/" + this.authLink.User.LocalId .
What happens is the both listeners are listening to each other and then causing a loop.
In that case it's probably better to use once instead of on if you are just using it once.
In cases where you cannot use .once, then you should use .off to turn off the listener once you are done.
firebaseApp.database().ref("Users/" + currentUser.uid + "/UserData").once('value'`
You also shouldn't be using await here since ref().on creates a listener, it doesn't return a promise.
You should also move history.push("/Demo") into your firebase database callback function so it's called after you have set data
Using the code below, I want to compare the UserType, if it is "Student" I want to redirect to student profile, etc.
But it always gets to the last else statement and Writes an Error.
The returnQuery method works well because it returns the value "Student".
String emailID = Session["New"].ToString();
string usertype = returnQuery(
"select userType from Registration where email = '" + lblEmail.Text + "'");
if (usertype.Contains("Student"))
{
Response.Redirect("Profile.aspx?email=" + emailID.ToString());
}
else if (usertype.Contains("Company"))
{
Response.Redirect("CompanyProfile.aspx?email=" + emailID.ToString());
}
else if(usertype.Contains("Admin"))
{
Response.Redirect("AdminProfile.aspx?email=" + emailID.ToString());
}
else
Response.Write("Error");
If usertype="Student" you can use usertype.Equals("Student"); to determine the variable.
Here is the method.
I suspect that you are dealing with a Page Lifecycle issue. lblEmail.Text is likely not what you expect it to be during Postback Event Handling time of the button click.
Verify that you are not modifying the contents of lblEmail.Text at any point before the button click event is processed, and verify the value of lblEmail.Text at the time the click event is processed.
For more information about Page Lifecycle, see this MSDN article:
https://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx
ok, i got it sorted thanks to LordALMMa, but now i have another problem. I want to determine if the user clicks Admin or User radiobutton when registering. I think i should append it to the end of the line on the text file where the name and password is, but how would i do it? Here is the relevant code:
Radio Button Check
public bool radioButtons()
{
string usertypebutton;
if (!userButton.Checked && !adminButton.Checked)
{
MessageBox.Show("You must select an account type");
return false;
}
else
{
if (userButton.Checked)
{
usertypebutton = "User";
}
else
{
usertypebutton = "Admin";
}
return true;
}
}
Streamwriter for registering:
public void mySW()
{
string path = #"C:\Other\myFile.txt";
string userName = userNameBox.Text;
string password = passwordBox.Text;
string usertype = usertypebutton;
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine("Username: {0} Password: {1} Type: {3}" , userName, password, usertype);
// No need to close nor dispose your StreamWriter.
// You're inside a using statement for that!
}
MessageBox.Show("Thanks for registering! \n\nYou may now log in!", "Registration SuccessFul");
Application.OpenForms[0].Show();
this.Close();
}
Logging In:
private void logonButton_Click(object sender, EventArgs e)
{
// Loads your users storage
var users = File.ReadAllLines(#"C:\Other\myFile.txt");
// Creates the line with username + password
var usernamePassword = String.Format("Username: {0} Password: {1}", userNameBox.Text, passwordBox.Text);
// Locates the user on your storage
var userFound = users.SingleOrDefault(_u => _u.Equals(usernamePassword));
if (userFound != null)
{
MessageBox.Show("Welcome back, " + userNameBox.Text);
}
else
{
MessageBox.Show("Sorry, you have entered incorrect details\n\nPlease try again");
userNameBox.Text = "";
passwordBox.Text = "";
}
}
So (I think) essentially i want to pass the value usertypebutton from radiobutton method, to the SW. How would i do it, as i'm already passing a boolean value?
Anthony
One part of the problem is that you are not writing the same string that you're reading:
writer.WriteLine("Password: " + userName + " " + "Password: " + password);
I'm guessing that was a typo in your post... but if not that could be your issue.
The other problem is probably this right here:
using (StreamWriter writer = new StreamWriter(path, true))
If you look up the documentation on that overload of the StreamWriter constructor, you'd see that you specified append = true. You are appending each set of login credentials to a file on its own line. But then later, you are only reading the first line of that file. So you will always read the first set of credentials that were entered when the file was first created.
That aside, I hope you are just doing this as an experiment since it is not a secure way of managing passwords to write them to a file like that. Also, you don't need to call Close and Dispose on a Stream if you wrap it in a using block, so you should stick to doing that.
Anthony, dispite the fact that storing logins this way is a major security problem (it's not even a risk anymore), there are some changes to your code that I'd do.
The issue is that you're not storing "Username: [username] Password: [password]".
If you double-check your saving method, you're storing "Password: [username] Password: [password]". That's why they are never found.
Here follows some changes:
Consider:
public void mySW()
{
string path = #"C:\Other\myFile.txt";
string userName = userNameBox.Text;
string password = passwordBox.Text;
using (StreamWriter writer = new StreamWriter(path, true))
{
// This overload makes your life easier by auto-formatting variables for you.
// Also, avoid the "string1 + string2" concatenation mode.
// Use String.Format instead. It's easier to read and keep over time.
writer.WriteLine("Username: {0} Password: {1}", userName, password);
// No need to close nor dispose your StreamWriter.
// You're inside a using statement for that!
}
MessageBox.Show("Thanks for registering! \n\nYou may now log in!", "Registration SuccessFul");
Application.OpenForms[0].Show();
this.Close();
}
And your other method should look like:
{
// Loads your users storage
var users = File.ReadAllLines(#"C:\Other\myFile.txt");
// Creates the line with username + password
var usernamePassword = String.Format("Username: {0} Password: {1}", userNameBox.Text, passwordBox.Text);
// Locates the user on your storage
// This uses Linq syntax with lambda. Linq without lamba looks similar to SQL.
// Lambda is a bit more advanced but reduces code-size and it's easier to understand (IMHO).
// This code will iterate through users (list of string) and try to retrieve one that's equal to the contents of usernamePassword.
var userFound = users.SingleOrDefault(_u => _u.Equals(usernamePassword));
// If null, indicates that no username/password combination was found.
if (userFound != null)
{
MessageBox.Show("Welcome back, " + userNameBox.Text);
}
else
{
MessageBox.Show("Sorry, you have entered incorrect details\n\nPlease try again");
userNameBox.Text = "";
passwordBox.Text = "";
}
}
I'm not checking for the exception. SingleOrDefault will throw an exception if 2 or more records are found mathing the search pattern.
I'm not checking that because this will increase complexity here with try-catch and also because for that to work properly, I'd have to check if they exits BEFORE recording, so changing the register method.
But I think you've got the idea here.
Have you checked your output files? You are writing Password: X Password: Y:
writer.WriteLine("Password: " + userName + " " + "Password: " + password);
and you are checking Username: X Password: Y
if (user == ("Username: "+userNameBox.Text.Trim()+" "+"Password: "+passwordBox.Text.Trim()))
You are adding line as
writer.WriteLine("Password: " + userName + " " + "Password: " + password);
^1 ^2
^1 must be Username:
There are some points which I cannot pass without pointing:
What would you do if file structure corrupted?
What if a user wants to register twice with same username and password?
Please encode the passwords. This is not ethic. You put at risk your members who uses same account information in somewhere else.
Try using a database which is stronger and faster than a text file.
I have the following code in C#:
if (function.Equals("Larger50"))
{
Request req = new Request();
string result = req.doRequest("function=" + function + "&num=" + number, "http://localhost:4000/Handler.ashx");
if (result.Equals("True") || result.Equals("true"))
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Larger.aspx?num=" + number + "', '_newtab')", true);
}
if(result.Equals("False") || result.Equals("false"))
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Smaller.aspx', '_newtab')", true);
}
if(result.Equals("Error") || result.Equals("error"))
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/ErrorPage.htm', '_newtab')", true);
}
Session["result"] = result;
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.location.href = 'Results.aspx'", true);
}
The result variable can have any one of three values (if the server responds):
i) true
ii) false
iii) error
The main problem with this code is that the new tab script in each of the three if statements work as they should. However, the last script which opens the Results.aspx page is not executing for some reason or another. The script is written well as it executed perfectly if all the other code is commented out. How should I solve the problem?
I tried replacing it with Response.Redirect("Results.aspx") however then this exeuctes and all the other three scripts never execute.
You should register these all at once, rather than in two separate statements:
if (function.Equals("Larger50"))
{
Request req = new Request();
string result = req.doRequest("function=" + function + "&num=" + number, "http://localhost:4000/Handler.ashx");
string scriptVal = "";
if (result.Equals("True") || result.Equals("true"))
{
scriptVal = "window.open('http://localhost:4000/Larger.aspx?num=" + number + "', '_newtab');";
}
if(result.Equals("False") || result.Equals("false"))
{
scriptVal = "window.open('http://localhost:4000/Smaller.aspx', '_newtab');";
}
if(result.Equals("Error") || result.Equals("error"))
{
scriptVal = "window.open('http://localhost:4000/ErrorPage.htm', '_newtab');";
}
Session["result"] = result;
scriptVal += "window.location.href = 'Results.aspx';";
Page.ClientScript.RegisterStartupScript(Page.GetType(), null, scriptVal, true);
}
See the docs on ClientScriptManager.RegisterStartupScript, specifically:
A startup script is uniquely identified by its key and its type.
Scripts with the same key and type are considered duplicates. Only one
script with a given type and key pair can be registered with the page.
Attempting to register a script that is already registered does not
create a duplicate of the script.
In your case, the type and key are the same in both of the scripts you register.
You could uniquely identify them with a key, and then register them separately. But you have to keep in mind that the order of execution is not guaranteed:
The script blocks are not guaranteed to be output in the order they
are registered.
I have a web project where clicking a button navigates to another page. The new page can be 1 of three possible pages depending on data in the server. (The url may be the same for 2 of those pages)
I have three classes representing expected elements on each page using the PageObject model.
What is the best way to actually find what page actually got loaded? Is there an OR type of wait that I can wait on three unique elements and get the one that actually got loaded?
Yes, it is possible to check the presence of unique element (which identifies the page) and then return respective page in the framework.
However, a test should know the page it is expecting next and should assume that the correct page has loaded and perform further actions/assertions. You can even put an assertion here to verify correct page has loaded. If a different page has loaded, then the test eventually fails as assertions would fail.
This way test becomes more readable and describes flow of application.
Also, setting up test data upfront for the tests, is always advisable. This way you would know what data is available on server and test would know which page would render.
I had a similar issue where I needed to detect if a login was for a new user (the login page then goes to a terms & conditions page rather than direct to the home page).
Initially I just waited and then tested the second page but this was just a pain so I came up with this.
To Test the result with this:
var whichScreen = waitForEitherElementText(By.CssSelector(HeaderCssUsing), "HOME SCREEN", "home", terms.getHeaderLocator(), terms.headerText, "terms", driver, MAX_STALE_RETRIES);
if(whichScreen.Item1 && whichScreen.Item2 == "terms")
{
terms.aggreeToTerms();
}
The method that this calls is :
protected Tuple<bool, string> waitForEitherElementText(By locator1, string expectedText1, string return1Ident,
By locator2, string expectedText2, string return2Ident, IWebDriver driver, int retries)
{
var retryCount = 0;
string returnText = "";
WebDriverWait explicitWait = new WebDriverWait(driver, TimeSpan.FromSeconds(globalWaitTime));
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0.5));
while (retryCount < retries)
{
try
{
explicitWait.Until<bool>((d) =>
{
try
{
if (Equals(d.FindElement(locator1).Text, expectedText1)) { returnText = return1Ident; };
}
catch (NoSuchElementException)
{
if (Equals(d.FindElement(locator2).Text, expectedText2)) { returnText = return2Ident; };
}
return (returnText != "");
});
return Tuple.Create(true, returnText);
}
catch (StaleElementReferenceException e)
{
Console.Out.WriteLine(DateTime.UtcNow.ToLocalTime().ToString() +
":>>> -" + locator1.ToString() + " OR " + locator2.ToString() + "- <<< - " +
this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name +
" : " + e.Message);
retryCount++;
}
}
return Tuple.Create(false,"");
}
The explicit wait until uses a boolean so will loop around for the full wait time (I have a very slow Test server so I set this to 60 seconds). the implicit wait is set to half a second so the element tests will attempt every half a second and loop around until either true is returned or it fails.
I use a Tuple so that I can detect which screen I am on, and in this case agree to the terms & conditions which then sets me back on my normal page path