What's the best practice for make username check like Twitter? - asp.net

I develop registration form and it have username field, and it's required to be like twitter username check ( real time check ) .. i already develop as in every textbox key up I use jquery to pass textbox.Text to page that return if is username exist or not
the following JavaScript method 'Check()' is invoked onkeyup for textbox :
function Check() {
var userName = $('#<%= TextBox1.ClientID %>').val();
if (userName.length < 3) {
$('#checkUserNameDIV').html("user name must be between 3 and 20");
return;
}
$('#checkUserNameDIV').html('<img src="loader.gif" />');
//setTimeout("CheckExistance('" + userName + "')", 5000);
CheckExistance(userName);
}
function CheckExistance(userName) {
$.get(
"JQueryPage.aspx", { name: userName },
function(result) {
var msg = "";
if (result == "1")
msg = "Not Exist " + '<img src="unOK.gif" />';
else if (result == "0")
msg = "Exist" ;
else if (result == "error")
msg = "Error , try again";
$('#checkUserNameDIV').html(msg);
}
);
}
but i don't know if is it the best way to do that ? specially i do check every keyup ..
is there any design pattern for this problem > or nay good practice for doing that ?

Maybe you could use a CustomValidator and a ServerSideValidationExtender with Ajax:

Related

Bootstrap validation without form tag in asp.net for particular button

In single page for two different buttons, Bootstrap validation without form tag in asp.net for particular buttons. Similar to like validation group.. Is there any way?
I think you have to do a trick for this...
1) Identify the classes that is applied on validate
2) Write a script to validate on click event for particular button
your script will be like
$("#btnId").click(function(){
var IsValid=true;
if($("#txtName").val()=="")
{
IsValid=false;
//Apply the classes that you have identified
$("#txtName").attr("class","className");
}
else
{
//Apply normal class
$("#txtName").attr("class","className");
}
if(IsValid)
{
return True;
}
else
{
return False;
}
});
this is only idea so don't look out the syntax.....
may this help
use customize jQuery on each button's Click
$('.login').on('click', LoginFunction);
$('.register').on('click', RegisterFunction);
function LoginFunction() {
var valid = true,
errorMessage = "";
if ($('#Login').val() == '') {
errorMessage = "please enter your Login \n";
valid = false;
}
if ($('#Password').val() == '') {
errorMessage += "please enter your PAssword\n";
valid = false;
}
if( !valid && errorMessage.length > 0){
alert(errorMessage);
}
}
function RegisterFunction() {
var valid = true,
errorMessage = "";
if ($('#name').val() == '') {
errorMessage = "please enter your name \n";
valid = false;
}
if ($('#address').val() == '') {
errorMessage += "please enter your address\n";
valid = false;
}
if ($('#email').val() == '') {
errorMessage += "please enter your email\n";
valid = false;
}
if( !valid && errorMessage.length > 0){
alert(errorMessage);
}
}

How to get Session obj value on client side from server js?

Hi as i mensioned above how to get the session variable from server to client js using meteor below placed the code verify and give me a sugession.In the bellow code how to get the ltest on client JS.
validation.Js:
Meteor.methods({
signupUser: function signupUser(rawData){
console.log("rawData :: "+rawData);
Mesosphere.signupForm.validate(rawData, function(errors, exmp){
if(!errors){
console.log("No Errors Found");
var username = '';
var password = '';
console.log(rawData.length + ">>>>>>>");
for(var i = 0;i < rawData.length ; i++)
{
var obj = rawData[i];
if(i == 0)
{
username = rawData[i].value;
console.log(rawData[i].value + ">>>>>>>" + obj.value);
}
else(i == 1)
{
password = rawData[i].value;
}
}
var obj = Meteor.call('ltest', username,password);
console.log("**********************"+obj);
//Session.set('q', obj);
//Do what you want with the validated data.
}else{
_(errors).each( function( value, key ) {
console.log("signupUser >> "+key+": "+value.message);
});
}
});
}
});
First of all, You need to use Future for this to return data from async call in method.
Second, Looks like you are trying to do code re-use with calling another meteor method.
IMO, you should not call the meteor method from another meteor method, which will create the another callback for getting results, which is added overhead and also make code unreadable. You should basically create the common function and try calling it from both Meteor method.
Following is listing, which should work
// define this future at top of file
Future = Npm.require("fibers/future")
Meteor.methods({
signupUser: function signupUser(rawData){
console.log("rawData :: "+rawData);
future = new Future()
Mesosphere.signupForm.validate(rawData, function(errors, exmp){
if(!errors){
console.log("No Errors Found");
var username = '';
var password = '';
console.log(rawData.length + ">>>>>>>");
for(var i = 0;i < rawData.length ; i++)
{
var obj = rawData[i];
if(i == 0)
{
username = rawData[i].value;
console.log(rawData[i].value + ">>>>>>>" + obj.value);
}
else(i == 1)
{
password = rawData[i].value;
}
}
//var obj = Meteor.call('ltest', username,password);
// replace above call to common method as described above
obj = common_ltest(username, password);
console.log("**********************"+obj);
future['return'](obj);
}else{
_(errors).each( function( value, key ) {
console.log("signupUser >> "+key+": "+value.message);
});
// assuming some error here, return null to client
future['return'](null);
}
});
// **note that, this important**
return future.wait()
}
});
Hope this helps

Reload page after file download via Response

I'm writing a reporting tool in which you can display a report straight to the page or download it as an excel file. In case you just want to show it on the page the site reloads as expected. in case it is downloaded as excel file the download works but the page is not reloaded. Thats a problem for me because I have no clue how to disable the loading animation afterwards. The download is accomplished with a write action to the response object. Here is the code:
private void ExcelExport(DataTable outList)
{
ViewBag.Reload = true;
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=report.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
Response.Output.Write(Excel.GetXml(outList));
Response.Flush();
Response.End();
}
The code is called from an ActionResult method within my controller (where the ExcelExport Method is also located):
public ActionResult WisPriceMatrix(string cc, string sl, string exp)
{
ViewBag.StorageLocations = this.StorageLocations;
ViewBag.WisPriceMatrixReport = null;
int cleanCode = 3;
if ((cc != null && cc != string.Empty && Int32.TryParse(cc, out cleanCode)) || (sl != null && sl != string.Empty))
{
sl = sl == string.Empty ? null : sl;
ViewBag.ParameterSl = sl;
ViewBag.ParameterCleanCode = cleanCode;
DataTable outList = dc.GetWisPriceMatrix(sl, cleanCode);
if (exp == null || exp == string.Empty || exp != "1")
{
ViewBag.WisPriceMatrixReport = outList;
}
else
{
if (outList.Count > 0)
{
this.ExcelExport(outList);
}
else
{
ViewBag.NoResults = "1";
}
}
}
return View();
}
Any Ideas how I could force the page to reload afterwards?
I tried to create a ViewBag variable that would indicate that a reload is neede and react to it via JavaScript but since the page isn't refreshed this is of nu success ;-).
In your case in order to reload page either you can use Viewbag and set Viewbag value on Controller say Viewbag.data="reload" and then on view check Viewbag as
$(document).ready(function(){
if('#Viewbag.data' == "reload")
{
window.location.reload(true);
}
});
OR you can just instead of return View() use return RedirectToAction("WisPriceMatrix") as RedirectToAction create a new http(302) request and reloads the page.

Modifying Netsuite Object on loading

I am very new to Netsuite. I am trying to do encryption in Netsuite. It works when I add UserEvent Scripts beforeSubmit. But I wanted to decrypt the encrypted text in beforeLoad function. I am able to read the encrypted text and decrypt it successfully as well. But setting it back in the object fails and I see decrypted text in Netsuite UI. Any directions or help is appreciated.
thanks
// this function works
function beforeSubmit(type) {
var email = nlapiGetFieldValue('email');
var newEmail = 'LifeSpan.' + email;
nlapiSetFieldValue('email', newEmail );
nlapiLogExecution('DEBUG', 'Modified before Submit ' + email + ' to ' + newEmail);
}
// this printed "Modified before Submit customercare#abc.com to LifeSpan.customercare#abc.com"
// this function doesn't work; even though the correct value is printed correctly in the log
function beforeLoad(type, form, request) {
var email = nlapiGetFieldValue('email');
if(email.indexOf('SaaSSpan.') != -1) {
var newEmail = email.substring(9);
nlapiSetFieldValue('email', newEmail );
nlapiLogExecution('DEBUG', 'Modified before load ' + email + ' to ' + newEmail);
}
}
// this printed "Modified before load LifeSpan.customercare#abc.com to customercare#abc.com"...but I am still seeing LifeSpan.customercare#abc.com in the user interface
I will suggest you to try this code in a client script(PageInit and SaveRecord Events).
Works fine for me.
My Code :
function PageInit(type) {
try {
if (type == 'edit') {
var email = nlapiGetFieldValue('email');
if (email != null && email.indexOf('LifeSpan.') != -1) {
var newEmail = email.substring(9);
nlapiSetFieldValue('email', newEmail);
nlapiLogExecution('DEBUG', 'Modified before load ' + email + ' to ' + newEmail);
}
}
}
catch (err) {
nlapiLogExecution('ERROR', 'PageInit', err);
}}
function SaveRecord() {
try {
var email = nlapiGetFieldValue('email');
var newEmail = 'LifeSpan.' + email;
nlapiSetFieldValue('email', newEmail);
nlapiLogExecution('DEBUG', 'Modified before Submit ' + email + ' to ' + newEmail);
}
catch (err) {
nlapiLogExecution('ERROR', 'SaveRecord', err);
}
return true;}
nlapiSetFieldValue can be used in user event beforeLoad scripts to initialize field on new records or non-stored fields.

Auto save of form

I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.

Resources