I cant type a "." with keycode - keypress

I have a problem with the geckoWebBrowser1 firefox browser component. In the geckoWebBrowser1_DocumentCompleted event I want to put an email address to a textbox.
I have to do that using the keypress event as the textbox requires the user to actually type the address. The code I have do work but there is a problem with the "." (dot) in the email: "myemail#hotmail.com"
I have found out the keycodes: 46 and 8228 is a "."
1. When I pass 46, it doesn't even type the "." in the textbox
2. When I pass 8228, it DO type the "." in the textbox but the webpage says that the email doesn't seem to be valid so it cant be a valid "."
My question is how to put a valid "." like I try to do.
Or if it is possible to inject the string itself DIRECTLY instead of using Keycodes?
private void geckoWebBrowser1_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e)
{
String emailaddress = "myemail#hotmail.com";
var element = geckoWebBrowser1.Document.GetElementById("login-email");
if (element != null)
{
DomEventArgs ev = geckoWebBrowser1.Document.CreateEvent("KeyEvents");
var webEvent = new Gecko.WebIDL.Event(geckoWebBrowser1.Window.DomWindow, ev.DomEvent as nsISupports);
webEvent.InitEvent("focus", true, false);
element.GetEventTarget().DispatchEvent(ev);
var nsIEventVar = ((nsIDOMKeyEvent)ev.DomEvent);
char[] inputChars = emailaddress.ToCharArray();
foreach (var vchar in inputChars)
{
int keyCode = 0;
if (vchar == '.')
{
keyCode = 46; //or 8228
nsIEventVar.InitKeyEvent(new nsAString("keypress"), true, false, geckoWebBrowser1.Window.DomWindow, false, false, false, false, (uint)keyCode, (uint)keyCode);
}
else
{
keyCode = (int)(System.Windows.Forms.Keys)vchar;
nsIEventVar.InitKeyEvent(new nsAString("keypress"), true, false, geckoWebBrowser1.Window.DomWindow, false, false, false, false, (uint)keyCode, (uint)keyCode);
}
Xpcom.QueryInterface<nsIDOMEventTarget>(element.DomObject).DispatchEvent(nsIEventVar);
}
}
}

I found a tricky way to solve it.
I first set an attribute value: ".com" (including the ".")
Then I start to keypress the rest of the email: "myemail#hotmail"
This did work and was then recogniced as a "."
elements.SetAttribute("value", ".com");
String emailaddress = "myemail#hotmail";

Related

How can I save and load textbox values, checkbox states, dropdown menu selections, etc., into a .txt file?

I am trying to implement a simple save-load function in my application, which would save the states of various GUI elements in my application (textboxes, checkboxes, dropdown menus, and so on) to a custom-named .txt file, and then load them back the next time user runs my application. I do not want to use My.Settings, because it is a portable application, and therefore the settings file has to be next to the executable. Also because my application is an editor, and the settings have to be bound by name to the current file the user is working with.
Write permissions is not an issue. I want to code this in a way so that I would only have to write down the names of the GUI elements to be mentioned once in my code, preferably in a list. Like this (pseudo-code):
'list
Dim ElementsToSave() as Object = {
Textbox1.text,
Checkbox1.Checked,
DropDownMenu1.SelectedItem,
.....
}
'save-load sub
Sub SaveLoad(Elements as Object, mode as string)
If mode = "save" then
For each Element in Elements
??? 'save each element state to .txt file
Next
If mode = "load" then
For each Element in Elements
??? 'load each element state from .txt file
Next
End if
End sub
'call
SaveLoad(ElementsToSave, "save")
'or
SaveLoad(ElementsToSave, "load")
I hope this conveys what I'm trying to achieve. Can anyone give any advice on how to make this work, please?
EDIT: I forgot to mention. It would be very nice if each value in the .txt file would be saved with a key that refers to a specific element, so that if I add more GUI elements in my application in the future, or re-arrange them, this save-load sub would always choose the correct value from the .txt file for a specific element.
using System.IO;
...
private enum ControlProperty
{
None = 0,
Text = 1,
Checked = 2,
SelectedValue = 3
}
private string GetSettingsFile()
{
FileInfo fi = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
string path = Path.Combine(fi.Directory.FullName, "settings.txt");
return path;
}
private void test()
{
SaveSettings();
LoadSettings();
}
private void SaveSettings()
{
object[] vals = new object[] { this.Textbox1, ControlProperty.Text, this.Textbox1.Text, this.Checkbox1, ControlProperty.Checked, this.Checkbox1.Checked, this.Menu1, ControlProperty.SelectedValue, this.Menu1.SelectedValue };
string txt = "";
for (int i = 0; i < vals.Length; i += 3)
{
string controlID = (vals[i] as Control).ID;
ControlProperty property = (ControlProperty)vals[i + 1];
object state = vals[i + 2];
txt += controlID + ":" + property.ToString() + ":" + state.ToString() + "\n";
}
string file = GetSettingsFile();
File.WriteAllText(file, txt);
}
private void LoadSettings()
{
string file = GetSettingsFile();
string[] lines = File.ReadAllLines(file);
foreach (string s in lines)
{
string[] parts = s.Split(':');
if (parts.Length < 3) continue;
string id = parts[0];
var c = this.form1.FindControl(id);
ControlProperty prop = ControlProperty.None;
Enum.TryParse<ControlProperty>(parts[1], out prop);
string state = parts[2];
if (c is TextBox && prop == ControlProperty.Text)
{
TextBox t = c as TextBox;
t.Text = state;
}
else if (c is CheckBox && prop == ControlProperty.Checked)
{
CheckBox chk = c as CheckBox;
chk.Checked = state == "True";
}
else if (c is Menu && prop == ControlProperty.SelectedValue)
{
Menu m = c as Menu;
foreach (MenuItem menuItem in m.Items)
{
if (menuItem.Value == state)
{
menuItem.Selected = true;
}
}
}
}
}

Setting dialog property value in SetValidate call does not work

Given the following formflow setup...
return builder
.Field(new FieldReflector<CarValuationDialog>(nameof(Mileage))
.SetValidate(async (state, value) =>
{
var result = new ValidateResult { IsValid = true };
if (int.TryParse(value.ToString(), out int mileage))
{
state.Mileage = mileage;
result.IsValid = true;
}
else
{
result.Feedback = "That isn't valid number. Can you enter it again please?";
result.IsValid = false;
}
return result;
}))
.Field(new FieldReflector<CarValuationDialog>(nameof(HappyWithAnswersBuying))
.SetActive(carValuationDialog => carValuationDialog.ValuationOption == ValuationOptions.LookingToOwn)
.SetPrompt(CreateHappyWithAnswersBuyingPrompt())
.SetDefine(HappyWithAnswersDefinitionMethod))
.OnCompletion(GetValuationAndDisplaySummaryToUser)
.Build();
I want to try out custom validation on the mileage answer given by the user. The code in SetValidate executes, and given a valid integer, that number is assigned to state.Mileage.
However, when the prompt asking the user if they are happy with the answers is shown, the mileage is still set to 0..
Here is the code for the prompt..
private static PromptAttribute CreateHappyWithAnswersBuyingPrompt()
{
StringBuilder sb = new StringBuilder(100);
sb.Append("Are you happy with your answers? <br /><br />");
sb.Append("{&RegistrationNumber}: {RegistrationNumber} <br />");
sb.Append("{&Mileage}: {Mileage:N0} miles {||}");
return new PromptAttribute(sb.ToString())
{
ChoiceStyle = ChoiceStyleOptions.Buttons,
FieldCase = CaseNormalization.InitialUpper
};
}
Before I added the SetValidate code, the mileage was shown perfectly fine in the prompt. But since I'm now manually setting state.Mileage, it's not being persisted across for some reason.
Man, I seriously need to "check the plug" on my code...
Basically I had not set the Value property of the ValidateResult instance...
.SetValidate(async (state, value) =>
{
var result = new ValidateResult { IsValid = true, Value = value };
....
}
After doing that, the mileage value now appears in the prompt...

Validation for textbox with two sets of phone numbers

I am trying to do a validation on a textbox that can allow the input of one or more phone number in a single textbox. What I am trying to do is to send an message to the phone numbers included in the textbox.
I have no problem when I enter just one set of number into the textbox and the message can be sent.
However, whenever I type two sets of digit into the same textbox, my validation error will appear.
I am using user controls and putting the user control in a listview.
Here are my codes:
private ObservableCollection<IFormControl> formFields;
internal ObservableCollection<IFormControl> FormFields
{
get
{
if (formFields == null)
{
formFields = new ObservableCollection<IFormControl>(new List<IFormControl>()
{
new TextFieldInputControlViewModel(){ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *" , IsMandatory = true, MatchingPattern = #"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},
});
}
return formFields;
}
}
And here is the codes for the button click event:
private void OkButton_Click(object sender, RoutedEventArgs e)
{
MessageDialog clickMessage;
UICommand YesBtn;
int result = 0;
//Fetch Phone number
var phoneno = FormFields.FirstOrDefault(x => x.Tag?.ToLower() == "phone").ContentToStore;
string s = phoneno;
string[] numbers = s.Split(';');
foreach (string number in numbers)
{
int parsedValue;
if (int.TryParse(number, out parsedValue) && number.Length.Equals(8))
{
result++;
}
else
{ }
}
if (result.Equals(numbers.Count()))
{
try
{
for (int i = 0; i < numbers.Count(); i++)
{
Class.SMS sms = new Class.SMS();
sms.sendSMS(numbers[i], #"Hi, this is a message from Nanyang Polytechnic School of IT. The meeting venue is located at Block L." + Environment.NewLine + "Click below to view the map " + Environment.NewLine + location);
clickMessage = new MessageDialog("The SMS has been sent to the recipient.");
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
YesBtn = new UICommand("Ok", delegate (IUICommand command)
{
timer.Stop();
idleTimer.Stop();
var rootFrame = (Window.Current.Content as Frame);
rootFrame.Navigate(typeof(HomePage));
rootFrame.BackStack.Clear();
});
clickMessage.Commands.Add(YesBtn);
clickMessage.ShowAsync();
}
}
catch (Exception ex)
{ }
}
}
I am trying to separate the two numbers with ";" sign.... and I am wondering if that is the problem. Or maybe it is the matchingpattern that I have placed in.
The answer is quite simple, create a bool property in your TextFieldInputControlViewModel something like
public bool AcceptMultiple {get;set;}
and to keep things dynamic, create a char property as a separator like below:
public char Separator {get;set;}
Now, modify your new TextFieldInputControlViewModel() code statement by adding values to your new fields like below:
new TextFieldInputControlViewModel(){Separator = ';', AcceptMultiple = true, ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *" , IsMandatory = true, MatchingPattern = #"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},
Once it's done, now in your checkValidation() function (or where you check the validation or pattern match) can be replaced with something like below:
if(AcceptMultiple)
{
if(Separator == null)
throw new ArgumentNullException("You have to provide a separator to accept multiple entries.");
string[] textItems = textField.Split(Separator);
if(textItems?.Length < 1)
{
ErrorMessage = "Please enter recipient mobile number." //assuming that this is your field for what message has to be shown.
IsError = true; //assuming this is your bool field that shows all the errors
return;
}
//do a quick check if the pattern matching is mandatory. if it's not, just return.
if(!IsMandatory)
return;
//your Matching Regex Pattern
Regex rgx = new Regex(MatchingPattern);
//loop through every item in the array to find the first entry that's invalid
foreach(var item in textItems)
{
//only check for an invalid input as the valid one's won't trigger any thing.
if(!rgx.IsMatch(item))
{
ErrorMessage = $"{item} is an invalid input";
IsError = true;
break; //this statement will prevent the loop from continuing.
}
}
}
And that'll do it.
I've taken a few variable names as an assumption as the information was missing in the question. I've mentioned it in the comments about them. Make sure you replace them.

NetSuite / Suitescript - Why does this Validate Field script enter an infinite loop?

My script is entering into an infinite loop and I have no idea why. I am running this on validate field and I am preventing a change to the field if another vendor bill exists with the same reference number, forcing the user to change the "Reference Number" to be unique. Here is my code:
function validateField(type, name) {
if (uniqueReferenceNum(type, name) === false) {
return false;
}
return true;
}
function uniqueReferenceNum(type, name) {
if (name !== 'tranid') {
return true;
}
var tranID = nlapiGetFieldValue('tranid');
var vendor = nlapiGetFieldValue('entity');
var vendorName = nlapiGetFieldText('entity');
var filters = new Array();
var columns = new Array();
filters[0] = new nlobjSearchFilter('entity', null, 'is', vendor);
filters[1] = new nlobjSearchFilter('tranid', null, 'is', tranID);
filters[2] = new nlobjSearchFilter('mainline', null, 'is', 'T');
columns[0] = new nlobjSearchColumn('internalid');
results = nlapiSearchRecord('vendorbill', null, filters, columns);
if (!results) {
return true;
}
alert("There is already a vendor bill with reference # " + tranID + " for " + vendorName + ". Please verify and change the reference number before continuing.");
return false;
}
For those still facing this issue, you can set the field in question - in this case, Reference Number - to a 'falsy' value such as an empty string. Only return false after checking that the field contains a 'truthy' value. Then display the alert or dialog to the user. This should break the validation loop.

How to delete a child domain row in grails

I am saving data to my entry meeting table as well as entry meeting details table which is a child table of entry meeting table. But When I want to delete only a child table record it's giving a error. I can't understand what to do. I am using grails 2.1.0. Can anyone please help me on this please ?!!! Here is my code below :
my parent domain >>>
class AdtEntryMeeting {
static mapping = {
table('ADT_ENTRY_MEETING')
version(false)
entryMeetingDetails cascade: 'all'
}
String meetingVenue
Date meetingDate = new Date()
String meetingTime
long CREATED_BY=0
Date CREATED_DATE=new Date()
long UPDATED_BY=0
Date UPDATED_DATE=new Date()
static hasMany = [entryMeetingDetails: AdtEntryMeetingDetails]
static constraints = {
meetingVenue(nullable: false, blank: false)
meetingDate(nullable: false)
meetingTime(nullable: false, blank: false)
CREATED_BY(nullable:true)
CREATED_DATE(nullable:true)
UPDATED_BY(nullable: true)
UPDATED_DATE(nullable: true)
}
String toString(){
return id
}
}
my child domain >>>
class AdtEntryMeetingDetails {
static mapping = {
table('ADT_ENTRY_MEETING_DETAILS')
version(false)
}
AuditFirm auditPack
AuditorDtl auditor
String meetingSubject
String responsiblePerson
AdtEntryMeeting entryMeeting
static constraints = {
auditPack(nullable: false, blank: false)
auditor(nullable: false, blank: false)
meetingSubject(nullable: false, blank: false)
responsiblePerson(nullable: false, blank: false)
entryMeeting(nullable: false, blank: false)
}
String toString(){
return auditPack
}
}
my action to delete >>>
if(params[isDelete + detailsCounter] == 'delete'){
def entryMeetingDetailsDelete = AdtEntryMeetingDetails.get(Long.parseLong(params[entryMeetingDetailsId + detailsCounter]))
entryMeetingDetailsDelete.delete()
}else{
def entryMeetingDetailsEdit = AdtEntryMeetingDetails.get(Long.parseLong(params[entryMeetingDetailsId + detailsCounter]))
entryMeetingDetailsEdit.properties['auditPack'] = AuditFirm.get(Long.parseLong(params[auditPack + detailsCounter]))
entryMeetingDetailsEdit.properties['auditor'] = AuditorDtl.get(Long.parseLong(params[auditor + detailsCounter]))
entryMeetingDetailsEdit.properties['meetingSubject'] = params[meetingSubject + detailsCounter]
entryMeetingDetailsEdit.properties['responsiblePerson'] = params[responsiblePerson + detailsCounter]
adtEntryMeetingInstance.addToEntryMeetingDetails(entryMeetingDetailsEdit)
}
the error I am getting >>>
deleted object would be re-saved by cascade (remove deleted object from associations)
You should first remove the reference from parent and then delete the child
e.g
def entryMeetingDetailsDelete = AdtEntryMeetingDetails.get(Long.parseLong(params[entryMeetingDetailsId + detailsCounter]))
adtEntryMeetingInstance.removeFromAdtEntryMeetingDetails(entryMeetingDetailsDelete)
entryMeetingDetailsDelete.delete()

Resources