Auto save of form - asp.net

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.

Related

How do scrape table from the provided website using casperjs?

The final goal is to retrieve stock data in table form from provided broker website and save it to some text file. Here is the code, that I managed to compile so far by reading few tutorials:
var casper = require("casper").create();
var url = 'https://iqoption.com/en/historical-financial-quotes?active_id=1&tz_offset=60&date=2016-12-19-21-59';
var terminate = function() {
this.echo("Exiting ...").exit();
};
var processPage = function() {
var rows = document.querySelectorAll('#mCSB_3_container > table'); //get table from broker site (copy/paste via copy selector in chrome tools)
//var nodes = document.getElementsByClassName('mCSB_container');
this.echo(rows);
this.echo(rows.length);
for (var i = 0; i < rows.length; i++)
{
var cell = rows[i].querySelector('.quotes-table-result__date');
this.echo(cell); //print each cell
}
};
casper.start(url);
casper.waitForSelector('#mCSB_3_container', processPage, terminate);
casper.run();
This code should retrieve the stock price table and print out each cell. However, all what I get is 'undefined', which likely means that I got no objects returned by queryselector call. And please assume that I don't know any web programming (HTML,CSS).
First of all, on problem is that the waitFor wasn't set so good, you have to wait for the rows/cells.
The Nodes you get out on this page are a bit wired,if anybody got a more abstract solution where ChildNodes are better handled that in my solution i would be really interested:
var casper = require('casper').create();
var url = 'https://eu.iqoption.com/en/historical-financial-quotes?active_id=1&tz_offset=60&date=2016-12-19-21-59';
var length;
casper.start(url);
casper.then(function() {
this.waitForSelector('#mCSB_3_container table tbody tr');
});
function getCellContent(row, cell) {
cellText = casper.evaluate(function(row, cell) {
return document.querySelectorAll('table tbody tr')[row].childNodes[cell].innerText.trim();
}, row, cell);
return cellText;
}
casper.then(function() {
var rows = casper.evaluate(function() {
return document.querySelectorAll('table tbody tr');
});
length = rows.length;
this.echo("table length: " + length);
});
// This part can be done nicer, but it's the way it should work ...
casper.then(function() {
for (var i = 0; i < length; i++) {
this.echo("Date: " + getCellContent(i, 0));
this.echo("Bid: " + getCellContent(i, 1));
this.echo("Ask: " + getCellContent(i, 2));
this.echo("Quotes: " + getCellContent(i, 3));
}
});
casper.run();

Javascript for CRM 2016 phones

I would like to ask about CRM Javascript code for phones, for example I have the following JS(Javascript) code for CRM web application it's not working with CRM phones
function checkCurrentUserInTeam(teamId) {
var serverUrl = "https://" + window.location.host;
var userId = Xrm.Page.context.getUserId();
if (teamId != null) {
var fwdFilter = "TeamMembershipSet?$filter=TeamId eq guid'" + teamId + "' and SystemUserId eq guid'" + userId + "'";
var url = serverUrl + "/xrmservices/2011/OrganizationData.svc/" + fwdFilter;
var fwdResult = GetOdataResults(url).results;
if (fwdResult != null && fwdResult.length > 0) {
return true;
}
else {
return false;
}
}
return false;
}
function GetOdataResults(url) {
CallOData(url);
str = CallOData(url);
var data = eval('(' + str + ')');
return data.d;
}
function CallOData(url) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
xmlhttp.setRequestHeader("Accept", "application/json, text/javascript, */*");
xmlhttp.send(null);
return xmlhttp.responseText;
}
I'm using checkCurrentUserInTeam function with team ID as parameter, and the error I think when XMLHttpRequest call the page in phones (See the below pic) .
Click here to view the image
I need your help if you have a specially code for CRM phones or some library for it. Any help in this regard will be highly appreciated.
Thanks ..
It might be the way you are creating your serverUrl. Try using getClientUrl instead.
var serverUrl = Xrm.Page.context.getClientUrl()

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

Not able to maintain checkbox during pagination using jQuery

I have 4 buttons for pagination(first,move next,move back and last).
I am trying to maintain checkbox during pagination. The problem is that
when I select any checkbox and then go to next page and then come back to the same page, it doesn't show previously checked checkbox, but as soon as click on next page, before going to next page it shows value checked.
Here is my code, can anyone guide me where I am doing wrong?
$(function() {
toggleSelectBtnOnCheck();
});
function toggleSelectBtnOnCheck() {
debugger;
//Register checkbox click handler to be called when Ajax requests complete.
$('#contentDiv').ajaxComplete(function() {
$('.tdHeadForCheckboxRadioButton').append('<input class="search" onclick="checkUnchekAllCheckboxes(this);" type="checkbox"/>');
$('.afirst, .aprev, .anext, .alast, .search:checkbox').click(function() {
var selectedVal = $(this).closest('td');
var selectClaim = selectedVal.next().text();
var selectSuffix = selectedVal.next().next().text();
var ClaimSuffix = selectClaim + '|' + selectSuffix + ',';
if ($(this).is(':checked')) {
document.getElementById('hdnChkClaim').value += ClaimSuffix;
} else if ($('#hdnChkClaim').val().indexOf(ClaimSuffix) != -1) {
$('#hdnChkClaim').val($('#hdnChkClaim').val().replace(ClaimSuffix, ''));
}
alert($('#hdnChkClaim').val());
if (jQuery(this).attr("href") != "") {
//button.disable($('span.btnSelect'));
var SelectedItemsCheckboxID = [];
if ($('#hdnChkClaim').val() != '') {
debugger;
if (ClaimSuffix.indexOf(',') != -1) {
ClaimSuffix = ClaimSuffix.substr(0, ClaimSuffix.length - 1); //remove last ','
}
SelectedItemsCheckboxID = $('#hdnChkClaim').val().split(',');
for (i = 0; i < SelectedItemsCheckboxID.length; i++) {
var claimDetails = SelectedItemsCheckboxID[i].split('|');
a = claimDetails[0];
b = claimDetails[1];
$('tr').filter(function(index) {
var columns = $(this).children('td');
alert(columns.eq(1).text() === a && columns.eq(2).text() === b);
return columns.eq(1).text() === a && columns.eq(2).text() === b;
}).find('input:checkbox').attr("checked", true);
;
}
}
if ($('.search:checkbox:checked').length > 0) {
button.enable($('span.btnSelect'));
} else {
button.disable($('span.btnSelect'));
}
}
});
});
}
You have to use the hidden field , when user select a checkbox , add it to hidden field like comma separated Ids , when every page is moved because of pagination check if any of the id in the current page is belong to the hidden field if yes mark them to checked.

runtime generated Checkbox validation

I have panel in the asp.net webpage, and i m generating the checkbox at runtime..
i want to validate checkbox, required field validator when form submit.
here is my code:
cv = new CustomValidator();
cv.ID = "cv" + "_" + dt.Rows[0]["RefQueID"].ToString();
cv.ValidationGroup = "grp";
cv.Display = ValidatorDisplay.None;
cv.ErrorMessage = "- Question " + intQuestionNo.ToString();
cv.ClientValidationFunction = "chkCount";
cv.Attributes.Add("rfvid", cv.ID.ToString());
//this portion of code is for custom validation javascript function
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'> function chkCount(sender,args) { ");
sb.Append(" args.IsValid = GetChk(document.getElementById('ctl00_ContentPlaceHolder1_" + cbl.ID.ToString() + "'))");
sb.Append(" } </script>");
Page page = HttpContext.Current.Handler as Page;
page.RegisterStartupScript("_Check", sb.ToString());
and in my javascript function i return this:
function GetChk(chkbox, args) {
if (!isConfirmed) {
alert('hi');
var chkBoxList = document.getElementById(chkbox.ClientID);
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}
but i m not getting the value of the checkbox...
required value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116_0
Actual Value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_complete_stage_chk_confirm
pls help...
first get the runtime generated control into the codebehind file from class file.
and then secondly after getting the control property, we can validate the checbox list.
Get the control into codebehind file from class file.
CheckBoxList cbl = (CheckBoxList)pnlref.FindControl("cbl_116");
provide the javascript validation to the runtime generated checkbox list.
function GetChk(chkbox, args) {
if (!isConfirmed) {
var chkBoxList = document.getElementById('ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116');
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}

Resources