Trying to jQuerify CEF browser in winform solution but the script is not executing, tried many methods but still it didn't work.
I am executing the script in the LoadingStateChanged .. already installed cefsharp from Nuget packages solution !
if there is another option better than CEFsharp please recommend !
string script = #"(function () {
// more or less stolen form jquery core and adapted by paul irish
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js', function () {
if (typeof jQuery == 'undefined') {
console.log('Sorry, but jQuery wasn\'t able to load');
} else {
console.log('This page is now jQuerified with v' + $.fn.jquery);
$(document).ready(function () {
alert(1);
//here you can write your jquery code
});
}
});
})();";
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate {
LoginchromeBrowser.ExecuteScriptAsync(script);
LoginchromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var startDate = response.Result;
MessageBox.Show(response.Result.ToString());
//startDate is the value of a HTML element.
}
});
});
}
else
{
LoginchromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var startDate = response.Result;
MessageBox.Show(response.Result.ToString());
//startDate is the value of a HTML element.
}
});
}
I'm using javascript to set the value of a cookie when I open the debugger panel so that if the user has already opened it, it will automatically open when they reload the page.
Here is the javascript:
jQuery(document).ready(function () {
DebuggingPanel.init(jQuery);
DebuggingPanel.GetPanelState();
});
DebuggingPanel.GetPanelState = function () {
jQuery.ajax({
url: "/sitecore modules/DebuggingPanel/DebuggingPanel.asmx/GetPanelState",
type: 'POST',
success: function(data) {
if (data.open === true) {
DebuggingPanel.TogglePanel();
}
}
});
}
DebuggingPanel.TogglePanel = function (changeState) {
var tinyDiv = $('.debuggingPanel.tinyDiv');
if (tinyDiv.text() == '+') {
tinyDiv.text('-');
DebuggingPanel.GetInformation();
DebuggingPanel.panel.slideDown();
interval = setInterval(DebuggingPanel.GetInformation, 5000);
if (changeState) {
DebuggingPanel.SetPanelState("open");
}
} else {
tinyDiv.text('+');
DebuggingPanel.panel.slideUp();
clearInterval(interval);
if (changeState) {
DebuggingPanel.SetPanelState("closed");
}
}
};
tinyDiv.click(function () {
DebuggingPanel.TogglePanel(true);
});
And here are the methods related to the cookie:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
In debugging the cookie looks as though it is getting the value correctly, but the next time I go into GetPanelState(), panelCookie.Value is always "" (not "open" as it should be, or "closed", which would indicate it was set by the toggle).
This happens when I reload the page, and it also happens when I call GetPanelState() at the end of SetPanelState(); panelCookie.Value = "open" in SetPanelState() but then equals "" in GetPanelState()
When you are reading from the Cookie, you need to use the Request instead of the response. So your code will be as follows:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
//It is here that you are reading the cookie.
var panelCookie = HttpContext.Current.Request.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
Thanks
I'm trying to implement a form validation with ASP.net and I have tried every solution suggested here but the best one was on aspsnippets.com so far.
My code is like below:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tTitle"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tEMail"/>
<asp:RegularExpressionValidator runat="server" ControlToValidate="tEMail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit"/>
Javascript
<script type="text/javascript">
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
{
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
} return true;
}
function WebForm_OnBlur() {
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
}
</script>
The problem is the e-mail field only validates for the regular expression. If I change the order of the validators, it only validates for required expression.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
Yes, this is indeed the problem. To fix it, you can do the following:
In the WebForm_OnBlur function, loop through the validators associated with the control that lost focus (rather than all the validators on the page), and clear the className property only if all the validators are valid:
function WebForm_OnBlur(control) {
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.className = "error";
return;
}
}
control.className = "";
}
In the onblur attribute of the TextBox controls, pass this as the argument to WebForm_OnBlur:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur(this)"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur(this)"/>
In the WebForm_OnSubmit function, call WebForm_OnBlur for each control that has associated validators:
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) === "function" && ValidatorOnSubmit() === false) {
for (var i = 0; i < Page_Validators.length; i++) {
var control = document.getElementById(Page_Validators[i].controltovalidate);
if (Page_Validators[i] === control.Validators[0]) // minor optimization
WebForm_OnBlur(control);
}
return false;
}
return true;
}
In addition to #MichaelLiu, You can make your own validators that inherit from the CustomValidator class and alter the rendering of the validators to make them a little easier to work with.
For example:
Validators.cs
Take notice of how we add a property of CssControlErrorClass. We will use this when applying a class with the invalid input in question.
We also set other properties so you don't have to set them everytime, ClientValidationFunction and ValidateEmptyText.
public class RequiredFieldValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public RequiredFieldValidator()
{
ClientValidationFunction = "validators.required";
ValidateEmptyText = true;
}
public string InitialValue
{
get
{
object o = ViewState["InitialValue"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
ViewState["InitialValue"] = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RequiredFieldValidation validator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null)
{
return true;
}
var result = (!controlValue.Trim().Equals(InitialValue.Trim()));
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if(!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
}
public class RegularExpressionValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public string ValidationExpression
{
get
{
object o = ViewState["ValidationExpression"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
try
{
Regex.IsMatch(String.Empty, value);
}
catch (Exception e)
{
throw new HttpException(string.Format("{0} - {1}", "Validator_bad_regex", value), e);
}
ViewState["ValidationExpression"] = value;
}
}
public RegularExpressionValidator()
{
ClientValidationFunction = "validators.regex";
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-regex", ValidationExpression);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RegularExpressionFieldvalidator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null || controlValue.Trim().Length == 0)
{
return true;
}
try
{
Match m = Regex.Match(controlValue, ValidationExpression);
var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length);
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if (!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
catch
{
return true;
}
}
}
Validators.js
Since in the previous classes we pre-defined the javascript functions, we can add a simple script like so:
var v = window.validators = window.validators || {
errorControlAttributeName: "data-for",
errorClassAttributeName: "data-errorClass",
regexAttributeName: "data-regex",
required: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
input = document.getElementById(controlId);
var isValid = (args.Value !== "");
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
regex: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
regexString = src.getAttribute(v.regexAttributeName),
input = document.getElementById(controlId),
regex = new RegExp(regexString);
var isValid = regex.test(args.Value);
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
/************* Helper functions ***********/
_toggleInputErrorState: function (inputEl, errorClass, isValid) {
if (!isValid) {
if (!v._hasClass(inputEl, errorClass)) {
inputEl.className += " " + errorClass;
}
} else {
if (v._hasClass(inputEl, errorClass)) {
//Not the most performant, but is sure is easiest
inputEl.className = inputEl.className.replace(" " + errorClass, "");
}
}
},
_hasClass: function(el, className) {
return el.className.indexOf(className) != -1 ? true : false;
},
}
Very simple validation library that you can easily extend with things you are actually interesting in.
Default.aspx
After than you can put the controls into your page:
<Validators:RequiredFieldValidator runat="server" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED BRO!"></Validators:RequiredFieldValidator>
<Validators:RegularExpressionValidator runat="server" ValidationExpression="[0-9]" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED RegEx BRO!"></Validators:RegularExpressionValidator>
Is this the best way? Probably not, (these two use the default implementation that is given by Microsoft) there are way smarter people out there than I and I don't work with WebForms much. The biggest benefit I see is that you get some reusable code, using a familiar syntax, that will eventually contain all your validation needs versus messing around with js everytime to get the validation "rules" how you want them.
The issue is resolved by replacing the code snippet below. To correct we must loop through all the validators for a control, then we should decide whether it has to marked with the error class. After this, your code will work as expected.
Replace the loop
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
}
with the below code
for (var j in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[j].controltovalidate);
var IsError = false;
for (var i in control.Validators) {
if (!control.Validators[i].isvalid) {
IsError = true;
}
}
if (IsError)
control.className = "error";
else
control.className = "";
} catch (e) { }
}
I just ran it and this is working excellently :) Try this solution!
you can try Page_ClientValidate() in javascript instead of looping across validator.
I believe this will validate all the validators on the page.
It also takes in parameter which "Validation group name" if you want to validate specific controls bound by particular validation group.
I am submitting a form in javascript to a controller in C# MVC it submits easily in chrome but not in Firefox and IE
//CSHTML CODE
<th class="gen2">
<button type="button" id="buttonClass">Generate</button>
</th>
<td class="money"><input type="checkbox" class="chk" name="checkboxID" value=#item.WithdrawalID></td>
//Javascript code
$("#buttonClass").click(function () {
getValueUsingClass();
});
function getValueUsingClass() {
var data = "";
var submitForm = document.createElement('form');
//Creating a form and giving the attributes
submitForm.name = "formSubmit";
submitForm.id = "formSubmit";
submitForm.method = "post";
submitForm.action = "generatebankfile";
var chkArray = \[\];
alert(chkArray);
$(".chk:checked").each(function () {
chkArray.push($(this).val());
});
for (var i = 0; i < chkArray.length; i++) {
data = data + chkArray\[i\];
if (i != chkArray.length - 1) {
data = data + ',';
}
}
var element = document.createElement("input");
element.name = "checkboxID";
element.value = data;
submitForm.appendChild(element);
if (chkArray.length > 0) {
submitForm.submit();
}
else {
alert("Please select at least one of the checkbox");
}
}
append form to the body
document.getElementsByTagName('body')[0].appendChild(submitForm);
I'm trying to run a validation on the textboxes of an asp page using javascript, but my second javascript function doesn't work as expected. I run the validation on the onblur event of each textbox, so I do:
<asp:TextBox ID="txtRegApellidoPat" runat="server" onblur="validaFormato(this);"> </asp:TextBox></td><td><asp:Label ID="valtxtRegApellidoPat" class="validaCad" runat="server">Únicamente texto</asp:Label>
Then on the textboxes that require integrers I do:
<asp:TextBox ID="txtRegEdad" runat="server" onblur="validaFormatoNum(this);"></asp:TextBox></td><td><asp:Label ID="Label1" class="validaNum" runat="server">* Solo números</asp:Label>
However this last function (validaNum) isn't working, and seems to return false always on the regularexpression.test method that I invoke.
My javascript code is like so:
<script type="text/javascript">
var formato = document.getElementById('formReg');
var textos = new Array("txtRegNombre", "txtRegApellidoPat", "txtRegApellidoMat", "txtRegEdo");
var numeros = new Array("txtRegEdad", "txtRegTel", "txtRegCP");
var pattern = /([A-Z]|[ÁÉÍÓÚáéíóúÄËÏÖÜäëïöü])+[^\d+]/g;
var pattern2 = /^\d$/g;
var invalidos1=document.getElementsByClassName("validaCad");
var invalidos2=document.getElementsByClassName("validaNum");
function validaFormato(obj) {
var valido = false;
if (!pattern.test(obj.value)&&!obj.value=="") {
invalidos1[0].style.display = "inline";
invalidos1[1].style.display = "inline";
invalidos1[2].style.display = "inline";
invalidos1[3].style.display = "inline";
return valido;
}
else {
invalidos1[0].style.display = "none";
invalidos1[1].style.display = "none";
invalidos1[2].style.display = "none";
invalidos1[3].style.display = "none";
valido = true;
}
return valido;
}
function validaFormatoNum(obj) {
var valido = false;
if (!pattern2.test(obj.value) && !obj.value == "") {
invalidos2[0].style.display = "inline";
invalidos2[1].style.display = "inline";
invalidos2[2].style.display = "inline";
return valido;
}
else {
invalidos2[0].style.display = "none";
invalidos2[1].style.display = "none";
invalidos2[2].style.display = "none";
valido = true;
}
return valido;
}
</script>
I'd really appreciate a hint on this as I can't realize what's the problem. The thing is that the number fields behave erratically, when I write a number on them the first time, the associated label doesn't show, which is correct behavior, but then when I tab through the form and tab out of the number field again, the label shows, as if the value was not a number, then on the following tab, the label doesn't show, then it shows, then it doesn't, etcetera.
I'm really at a loss when it comes to regular expressions so I don't know if the problem is with my second RegExp, but it's simply asking to have a number at the beginning and end of the string, isn't it?
I guess you have to change
var pattern = /([A-Z]|[ÁÉÍÓÚáéíóúÄËÏÖÜäëïöü])+[^\d+]/g;
to (move the + out of the character class):
var pattern = /([A-Z]|[ÁÉÍÓÚáéíóúÄËÏÖÜäëïöü])+[^\d]+/g;
that could be rewritten:
var pattern = /[A-ZÁÉÍÓÚáéíóúÄËÏÖÜäëïöü]+\D+/g;