Validating required fields and confirming fields in c# visual studio - c#

I am having trouble with creating a form that requires the user to enter information in the fields, Confirm an email and password entry, and go onto the next form when all those fields are matched/filled in. Individually, the code I have works, but I cannot seem to find a way to make it so that all the requirements are met before going onto the next form. At the moment it just goes onto the next form if i click the continue button.
some excerpts of the code i have are:
if (string.IsNullOrEmpty(email))
{
lblRequirementsError.Text = ("All required fields have not been filled.");
}
if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}
if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}
this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();

The problem is the form is created and opened regardless of the if results, because the code for it is outside the ifs. First, check that no fields are empty, and then, check that the validation has been met, THEN open the new window. Something like this should work:
//If both email and password are not empty
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
//if both email and password math the re entry
if (txtBoxEmail.Text == txtBoxConfirmEmail.Text &&
txtBoxPassword.Text == txtBoxConfirmPassword.Text)
{
//execute the code to open the new form
this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
}
}

if (! txtBoxEmail.Text.Equals( txtBoxConfirmEmail.Text))
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}
if (! txtBoxPassword.Text.Equals( txtBoxConfirmPassword.Text))
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}

are you using web applications forms in visual studio 2012. You can use field validators inside the .ASPX file for any field that you want to validate before form submission. This is much easier that writing everything in C#.

You can use the DataAnnotation if you are binding or converting your controls to the data objects. Then it will be easy to validate. Please see the link for more details
http://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx

Try this:
bool validationStatus = default(bool);
if (string.IsNullOrEmpty(email))
{
lblRequirementsError.Text = ("All required fields have not been filled.");
validationStatus = true;
}
if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
validationStatus = true;
}
if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
validationStatus = true;
}
if(!validationStatus)
{
Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
}

Related

Cannot interact an element because Windows Inspect cannot show that element in question - WinAppDriver + Selenium?

I need an advise from those who have more experience on automating a window desktop application.
I cannot automate a test in a certain form because I believe it cannot be done as Win Inspect cannot really see them. I will show you 2 images below what I meant by this.
this image is an example where I CAN automate the button Close using the following BDD, because Win Inspect can see it.
Scenario Outline: IP120929-00060 - I Check Button
Then Button "Close" Is Displayed
the image below is an example where I CANNOT automate the button Close using the same BDD & test definition (and method), because (I believe) Win Inspect cannot see it (however the properties of that element in question can be viewed)
Scenario Outline: IP99999_DEL_ME-00099 - I Check Button
Then Button "Close" Is Displayed
The Test Definition/Binding for that BDD is:
[Then(#"Button ""(.*)"" Is Displayed")]
public void ThenButtonIsDisplayed(string button)
{
var proc = $"Then Button {button} Is Displayed";
if (CombinedSteps.OutPutProc(proc, OutputLevel.Then))
{
if (Helpers.Button.**Displayed**(button, 3))
{
CombinedSteps.Success();
return;
}
}
CombinedSteps.Failure(proc);
}
public bool **Displayed**(string button, int timeout = 3, string windowName = "")
{
DebugOutput.Log($"Proc - Displayed {button} {timeout} '{windowName}' CurrentPage = {CurrentPage.ToString()}", OutputLevel.Procedure);
if (windowName != "")
{
DebugOutput.Log($"We need to narrow down by window");
return DisplayedByWindow(button, windowName, timeout);
}
var buttonId = CurrentPage.GetElement(button);
if (buttonId == null)
{
DebugOutput.Log($"Did not find a mention of that element in forms Element Factory, ");
return false;
}
var buttonLocator = buttonId.Locator;
DebugOutput.Log($"Find Element by {buttonLocator} ");
if (!JustOneButtonToPress(buttonLocator))
{
var currentPageName = CurrentPage.Name.ToLower();
currentPageName = currentPageName.Replace(" page", "");
var buttonInWindowElement = GetButtonElementInWindow(currentPageName, button);
if (buttonInWindowElement == null)
{
DebugOutput.Log($"Even in window I'm failing to find {button} {currentPageName}");
return false;
}
DebugOutput.Log($"Found in the window - it will click the first that fits under the window");
return buttonInWindowElement.Displayed;
}
DebugOutput.Log($"Got the locator of {buttonLocator}");
var buttonElement = SeleniumUtilities.GetElement(CurrentPage.GetElement(button).Locator, timeout);
if (buttonElement == null)
{
DebugOutput.Log($"Did not find a mention of that element in form");
return false;
}
DebugOutput.Log($"It exists {buttonElement}");
return buttonElement.Displayed;
}
the code will always return buttonElement as null for the Create Curves window form
Its frustrating thing trying to make this works, so my question to know better and have more experience, is this a limitation of the Desktop Application I am testing or is there another way around this? Is it better to ask the Developer to change something about it in the Application?
I have tried to map the 'Close' button in question using it's ID, Name and/or XPath - but all to no avail
any guidance on this would be much appreciated.
Cheers.

Iterate through Controls to find errorProviders c# WinForm

Overview of function.
I have this SaveDetails function within a WinForm, which iterates through all of the controls, to determine whether any errorProviders have been flagged in the form during the users input. If the function returns true,
all of my TextBoxes values need to be stored in my private fields, and display a messsagebox and close the form.
// For about 15 textBoxes, Could this be achieved also by looping? As this looks very cumbersome.
title = cmb_Title.Text;
If returns false and an errorProvider has been found in the iteration, it needs to display an error message for the user, clear private fields and give the user chance to re-enter details, however not clear textBoxes!!
Issue:
the loop iterates through everything, all of the controls regardless if it has found an errorProvider. How can I stop this to just flag when just one has been found? This function is also in a clickEvent.
Code
isValid = true;
foreach (Control c in panel1.Controls)
{
if (errorProvider1.GetError(c).Length > 0)
{
isValid = false;
MessageBox.Show("invalid entry, please revisit the form before proceding");
}
}
if (isValid)
{
title = cmb_Title.Text;
surName = txt_SurName.Text;
dateOfBirth = dateTimePicker1.Text.ToString();
MessageBox.Show("Indi Form Saved");
Hide();
}
you can shorten it using only TextBox controls and Linq.
Something like this:
List<TextBox> textBoxes = panel1.Controls.OfType<TextBox>().ToList();
if (textBoxes.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
MessageBox.Show("invalid entry, please revisit the form before proceding");
If you don't want to check only TextBox controls but all controls in panel1, you can still use Linq to simplify your code.
var controlsList = panel1.Controls.Cast<Control>().ToList();
if (controlsList.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
MessageBox.Show("invalid entry, please revisit the form before proceding");

Sitecore Rich Text editor customisation of link Insertions

When a user uses the "Insert Link" feature on the RTE to create stories, we get something like...<Item-Name-Of-Story
Instead of taking the Item name I would like to use another field called "Headline"
Does anyone know how to do this?...
Headline-Of-Story
Any help will be much appreciated. Thanks
First of all, you need need to look at this class with Reflector or DotPeek : Sitecore.Shell.Controls.RichTextEditor.InsertLink.InsertLinkForm and to modify it with your own class.
You need to modify just this method,I tested and works fine :
protected override void OnOK(object sender, EventArgs args)
{
Assert.ArgumentNotNull(sender, "sender");
Assert.ArgumentNotNull((object) args, "args");
string displayName;
string text;
if (this.Tabs.Active == 0 || this.Tabs.Active == 2)
{
Item selectionItem = this.InternalLinkTreeview.GetSelectionItem();
if (selectionItem == null)
{
SheerResponse.Alert("Select an item.", new string[0]);
return;
}
else
{
displayName = selectionItem["Headline"];
if (selectionItem.Paths.IsMediaItem)
text = CustomInsertLinkForm.GetMediaUrl(selectionItem);
else if (!selectionItem.Paths.IsContentItem)
{
SheerResponse.Alert("Select either a content item or a media item.", new string[0]);
return;
}
else
{
LinkUrlOptions options = new LinkUrlOptions();
text = LinkManager.GetDynamicUrl(selectionItem, options);
}
}
}
else
{
MediaItem mediaItem = (MediaItem) this.MediaTreeview.GetSelectionItem();
if (mediaItem == null)
{
SheerResponse.Alert("Select a media item.", new string[0]);
return;
}
else
{
displayName = mediaItem.DisplayName;
text = CustomInsertLinkForm.GetMediaUrl((Item) mediaItem);
}
}
if (this.Mode == "webedit")
{
SheerResponse.SetDialogValue(StringUtil.EscapeJavascriptString(text));
base.OnOK(sender, args);
}
else
SheerResponse.Eval("scClose(" + StringUtil.EscapeJavascriptString(text) + "," + StringUtil.EscapeJavascriptString(displayName) + ")");
}
After you modify this class you need to modify next file:
\sitecore\shell\Controls\Rich Text Editor\InsertLink\InsertLink.xml where you need to change codeBeside section
<CodeBeside Type="Sitecore.Shell.Controls.RichTextEditor.InsertLink.InsertLinkForm,Sitecore.Client"/>
with something like :
<CodeBeside Type="YourNameSpace.YourInsertLinkForm,YourAssembly"/>
The simplest way around this would be to type the desired link text, then select this before clicking 'insert link' - this way your hyperlink will have the text of whatever you entered, instead of defaulting to the item name.
If you want to modify how Sitecore renders links in RTE fields, you would need to modify the <renderField> pipeline - if you search for this in the web.config, you will see the different classes involved here. Using dotPeek you can decompile the Sitecore source to see how this works. Potentially you could then create your own renderField pipeline handler to change the link rendering behaviour and then reference this new class in your web.config.

What button pressed inputbox C#

I am using the input box from visual basic in c# and I couldn't figure out how I know what button has been pressed. The input box return the string that has been written.
How I know if the cancel button has been clicked or the OK button?
Thank you very much for the help, I didn't find the answer :)
This is what I tried:
string notineName = Interaction.InputBox("Enter the notice name:", "Enter notice name", "");
If you have another way to do input box ( I wanted to make my own but I don't know how to return what button has been clicked) please write it here.
If the user clicks Cancel, a zero-length string is returned.
Try having a look at this documentation. MSDN
As an alternative you could use dialog boxes.
InputDialog dialog = new InputDialog("Caption Here", "Label Text Here", "Default Textbox String");
if (dialog.ShowDialog() == DialogResult.OK)
{
string result_text = dialog.ResultText;
// use result_text...
}
else
{
// user cancelled out, do something...
}
Here an enum result determines what button was selected.
string a;
a = Interaction.InputBox("message", "message");
if (a.Length > 0)
{
comboBox2.Items.Add(a);
// ok
}
else
{
// cancel
}

Detecting input consisting of just spaces

I have a wepage for a user to sign up,i have tested it and runned it,i was testing it using space not entering any words to signup,meaning a user can signup without entering any words just by using space.so i dont want this to happen to my webpage.
any one who has some code that i can use to validate this...
You can use the method: string.IsNullOrWhiteSpace to check
either the simple string.IsNullOrWhiteSpace
or if you really want to use the answer you chose, you should edit it to:
if (firstName ! = null && lastName ! = null)
{
if (firstName.Trim()=="" || lastName.Trim()=="")
{
return False;
}
else
{
return True;
}
}
else return False;
you can validate user input in many ways. One of them is to use built in Visual Studio Vaidator controls and make sure that each control is tighed to a text box in your form and its preoperty is selected to ensure the field is filled before submitting the form.
Another way is to do the validation from the code behind. Something like this:
if (firstName.Trim()=="" || lastName.Trim()=="")
{
return False;
}
else
{
return True;
}

Categories

Resources