Post request in web view windows phone - using C# - c#

I am trying to achieve the same thing, but I am getting exception when I call the InvokeScript method, Please help. I used this link (Post data with a request in a Windows Store app WebView - using C#) to code, Here is my JV
webview.NavigateToString(#"<html>
<head>
<script type='text/javascript'>
function doSomething(userIdValue, sessionIdValue)
{
document.getElementById('Username').value = userIdValue;
document.getElementById('Password').value = sessionIdValue;
document.getElementById('myForm').submit();
return 'Hello World!';
}
</script>
</head>
<body>
<form id='myForm' action='http://integr-dev-ma.test.plano/myplano/Account/Login' method='post'>
<input type='hidden' id='ext-element-18' name='Username' />
<input type='hidden' id='ext-element-24' name='Password' />
</form>
</body>
</html>");
When I call this script I get following Exception
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
// this.Frame.Navigate(typeof(SettingsPage));
try
{
await webview.InvokeScriptAsync("doSomething", new string[] { "30001", "12345" });
}
catch (Exception aex)
{
string messages = "";
messages += aex.Message + "\r\n";
System.Diagnostics.Debug.WriteLine(messages);
}
I resolved above problem, there was problem in Javascript, The ID was written wrong in following code
document.getElementById('Username').value = userIdValue;
document.getElementById('Password').value = sessionIdValue;
The Username and Password should have been "ext-element-18" and "ext-element-18". Correcting javascript removed the exception. Now the basic aim of this request was to login in the webview.
My other team has developed the webpart, they have used sanchatouch framework so in the HTML code of login page there are no <form> tags so submitting this didn't work. I was not logged in, I am posting source of the login page, may be someone can help on this. When the user clicks on login button normally loginfunction is called, you can locate in code but anyhow I need to do post request to automate login
<!DOCTYPE html>
<html>
<head>
<!-- General Meta things -->
<meta charset="utf-8" />
<title>Login - myplano</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--<link href="/myplano/Content/Stylesheets/myplano.css" rel="stylesheet"/>
<link href="/myplano/Scripts/Sencha/resources/css/sencha-touch.css" rel="stylesheet"/>
-->
<link href="/myplano/Scripts/Sencha/resources/css/cupertino.css" rel="stylesheet"/>
<link href="/myplano/Content/Stylesheets/myplano.css" rel="stylesheet"/>
<!-- Apple Meta things -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="white-translucent" />
<link rel="apple-touch-icon" sizes="144x144" href="/myplano/Content/Images/App_Icons/Apple/myplano144.png">
<link rel="apple-touch-icon" sizes="57x57" href="/myplano/Content/Images/App_Icons/Apple/myplano57.png">
<link rel="apple-touch-icon" sizes="72x72" href="/myplano/Content/Images/App_Icons/Apple/myplano72.png">
<link rel="apple-touch-icon" sizes="114x114" href="/myplano/Content/Images/App_Icons/Apple/myplano114.png">
<link rel="apple-touch-startup-image" href="/myplano/Content/Images/App_Icons/Apple/apple_startup.png">
<!-- Android Meta things -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#384093">
<link rel="icon" sizes=”192×192″ href="/myplano/Content/Images/App_Icons/Android/myplano192.png">
<!-- Windows meta things -->
<!-- TODO: Icon size needs to be 310x310 -->
<meta name="application-name" content="myplano" />
<meta name="msapplication-TileColor" content="#384093" />
<meta name="msapplication-square70x70logo" content="/myplano/Content/Images/App_Icons/Windows/tiny.png" />
<meta name="msapplication-square150x150logo" content="/myplano/Content/Images/App_Icons/Windows/square.png" />
<meta name="msapplication-wide310x150logo" content="/myplano/Content/Images/App_Icons/Windows/wide.png" />
<meta name="msapplication-square310x310logo" content="/myplano/Content/Images/App_Icons/Windows/large.png" />
<meta name='msapplication-navbutton-color' content='#384093' />
<meta name='msapplication-tooltip' content='start myplano' />
<meta name="msapplication-window" content="width=800;height=1024;" />
<!--<meta name='msapplication-starturl' content='http//domain.de' />-->
<!-- This script is required for the swipe calendar-->
<!--<script type="text/javascript" src="/myplano/Scripts/myplano/momentjs/moment.js"></script>
-->
</head>
<body>
<script type="text/javascript">
var baseUrl = "/myplano/";
</script>
<script src="/myplano/Scripts/Sencha/sencha-touch-all.js"></script>
<script src="/myplano/Scripts/Sencha/src/ux/picker/DateTime.js"></script>
<script src="/myplano/Scripts/Resources/Resource-de.js"></script>
<script type="text/javascript">
Ext.Date.defaultDateFormat = "d.m.Y";
Ext.Date.defaultTimeFormat = "H:i";
Ext.Date.defaultTimeHMSFormat = "H:i:s";
Ext.Date.defaultFullDateTimeFormat = "d.m.Y H:i:s";
var localLanguage = 'en';
</script>
<script src="/myplano/Scripts/myplano/momentjs/moment.js"></script>
<script src="/myplano/Scripts/Controls/Timefield.js"></script>
<script src="/myplano/Scripts/Controls/DateTimePicker.js"></script>
<script src="/myplano/Scripts/myplano/Base.js"></script>
<script src="/myplano/Scripts/myplano/MainMenu.js"></script>
<script src="/myplano/Scripts/myplano/Views/AccountValues.js"></script>
<script src="/myplano/Scripts/myplano/Views/Profile.js"></script>
<script src="/myplano/Scripts/myplano/Views/RequestList.js"></script>
<script src="/myplano/Scripts/myplano/Views/TimeStamps.js"></script>
<script src="/myplano/Scripts/myplano/Views/Calendars/DayCalendar.js"></script>
<script src="/myplano/Scripts/myplano/Views/Calendars/MonthCalendar.js"></script>
<script src="/myplano/Scripts/myplano/Views/Calendars/WeekCalendar.js"></script>
<script src="/myplano/Scripts/myplano/Views/Calendars/GroupCalendar.js"></script>
<script src="/myplano/Scripts/myplano/Views/Calendars/Calendar_Shared.js"></script>
<script src="/myplano/Scripts/myplano/Views/Requests/FullDay.js"></script>
<script src="/myplano/Scripts/myplano/Views/Requests/RequestTypeList.js"></script>
<script src="/myplano/Scripts/myplano/Views/Requests/NewRequest.js"></script>
<script src="/myplano/Scripts/myplano/Views/ApproverList.js"></script>
<script src="/myplano/Scripts/myplano/placeholder.js"></script>
<script src="/myplano/Scripts/myplano/util/PaintMonitor.js"></script>
<script src="/myplano/Scripts/myplano/util/SizeMonitor.js"></script>
<script src="/myplano/Scripts/myplano/shared.js"></script>
<script src="/myplano/Scripts/myplano/TransponderUi.js"></script>
<div>
<script type="text/javascript">
var userTextfield = new String;
Ext.setup({
onReady: function () {
// create local user model
Ext.define('LocalUser', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: "id" },
{ name: "username", type: "string" },
{ name: "firstname", type: "string" },
{ name: "lastname", type: "string" },
{ name: "globalmessage", type: "string" },
{ name: "employeemessage", type: "string" }
],
proxy: {
type: 'localstorage',
id: 'local-user'
}
}
});
var store = Ext.create('Ext.data.Store', {
model: 'LocalUser'
});
store.load();
var storageCount = store.getAllCount();
if (storageCount > 0) {
//console.log(storageCount + " users found");
var userObject = store.getAt(storageCount - 1);
var user = userObject.get("username");
userTextfield = user;
//console.log("last logged in user was: " + userTextfield);
}
//login
var login = function () {
var label = form.down("[itemId='signInFailedLabel']");
var btn = form.down("button");
label.hide();
btn.setDisabled(true);
form.setDisabled(true);
btn.setText(plano.myplano.Resources.Get("LogingIn"));
//login
Ext.Ajax.request({
url: plano.Base.ResolveUrl('~/Account/Login'),
method: 'POST',
params: form.getValues(),
success: function (response) {
var data = Ext.decode(response.responseText);
if (data.error) {
label.setHtml(data.error);
label.show();
form.setValues({
Username: "",
Password: ""
});
btn.setText(plano.myplano.Resources.Get("LoginDescription"));
btn.setDisabled(false);
form.setDisabled(false);
}
else if (data.success) {
var firstName = "";
var lastName = "";
var globalMessage = "";
var employeeMessage = "";
//if new password needed
if (data.newPasswordNeeded)
{
location.href = plano.Base.ResolveUrl('~/Account/ResetPassword');
};
Ext.Ajax.request({
url: plano.Base.ResolveUrl("~/Home/getEmployeeName"),
success: function (result) {
var resultData = Ext.decode(result.responseText);
console.log(resultData);
console.log("Employee Name");
console.log(resultData.data['FirstName'] + " " + resultData.data['LastName']);
firstName = resultData.data['FirstName'];
lastName = resultData.data['LastName'];
//Store Username
var thisuser = form.down("textfield").getValue();
Ext.Ajax.request({
url: plano.Base.ResolveUrl("~/Home/getWelcomeText"),
success: function (result2)
{
var resultData2 = Ext.decode(result2.responseText);
console.log("WelcomeText");
console.log(resultData2['employeeMessage']);
globalMessage = resultData2['globalMessage'];
if (resultData2['employeeMessage'])
{
employeeMessage = resultData2['employeeMessage'];
}
var store = Ext.create('Ext.data.Store', {
model: "LocalUser"
});
store.load();
store.getProxy().clear();
store.data.clear();
store.add({
username: thisuser,
firstname: firstName,
lastname: lastName,
globalmessage: globalMessage,
employeemessage: employeeMessage
});
store.sync();
location.href = plano.Base.ResolveUrl('~/');
}
});
}
});
}
},
error: function (errorResponse) {
Ext.Msg.alert('Error', 'Login request failed');
}
});
};
var form = Ext.create('Ext.form.Panel', {
fullscreen: true,
id: 'loginForm',
scrollable: null,
baseCls: 'login-form',
config: {
//scrollable: false
},
layout: {
type: 'vbox',
pack: 'center',
align: 'center'
},
items: [
{
xtype: 'panel',
hideAnimation: 'fadeOut',
showAnimation: 'fadeIn',
itemId: 'myplanoLogo',
html: '<img id="logo" class="login-myplano-logo" src="/myplano/Content/Images/Vector/myplano.svg" />' //~/Content/Images/myplano 256x256.png
}, {
xtype: 'fieldset',
baseCls: 'login-form',
//title: plano.myplano.Resources.Get("LoginTitle"),
defaults: {
margin: '5px 0',
listeners: {
action: login
}
},
items: [
{
xtype: 'panel',
html: '<div class="separator-login"></div>'
},
{
xtype: "textfield",
clearIcon: false,
baseCls: 'login-form',
placeHolder: plano.myplano.Resources.Get("UserName"),
value: userTextfield,
name: "Username",
required: true
}, {
xtype: "passwordfield",
clearIcon: false,
baseCls: 'login-form',
placeHolder: plano.myplano.Resources.Get("Password"),
name: "Password",
required: true
}, {
xtype: 'button',
cls: 'login-button',
labelCls: 'x-button-label login-button-label',
text: plano.myplano.Resources.Get("LoginDescription"),
margin: '5px auto',
handler: login
}]
}, {
xtype: 'label',
itemId: 'signInFailedLabel',
hidden: true,
//hideAnimation: 'fadeOut',
//showAnimation: 'fadeIn',
style: 'color: #FF8888; text-align: center;',
margin: "6 12 6 12"
}, {
xtype: 'label',
itemId: 'vernsionInfo',
docked: 'bottom',
style: 'text-align: center; color:#FFF; font-size: 0.5em;',
margin: "0 0 5px 0",
html:
'myplano' +
' Version 1' + '.' +
'2' +
' Rev. 73666'
}, {
xtype: 'panel',
docked: 'bottom',
itemId: 'planoLogo',
//hideAnimation: 'fadeOut',
//showAnimation: 'fadeIn',
//margin: '5% 0 0 0',
html: '<img id="logo" class="login-plano-logo" src="/myplano/Content/Images/Vector/plano_logo_white.svg" />' //~/Content/Images/myplano 256x256.png
}]
});
//hide image if soft keyboard is shown
var myplanoLogo = form.down("[itemId='myplanoLogo']");
var planoLogo = form.down("[itemId='planoLogo']");
window.onresize = function () {
// If the current active element is a text input, we can assume the soft keyboard is visible.
var windowWidth = Ext.getBody().getWidth(true);
var windowHeight = Ext.getBody().getHeight(true);
if (windowWidth < windowHeight)
{
//keyboard is shown
console.log("keyboard on");
myplanoLogo.show();
planoLogo.show();
} else {
//keyboard is hidden
console.log("keyboard off");
myplanoLogo.hide();
planoLogo.hide();
}
}
}
});
</script>
</div>
<script src="/myplano/Scripts/jquery-2.1.1.js"></script>
</body>
</html>
<script>
//back button disabled
document.addEventListener("backbutton", Ext.bind(onBackKeyDown, this), false);
function onBackKeyDown(eve)
{
eve.preventDefault();
//do something
alert('back button pressed');
}
//this script checks if user is idling
var timeoutInMinutes = "20";
//console.log("timeout in " + timeoutInMinutes + " minutes.")
var IDLE_TIMEOUT = timeoutInMinutes*60; //seconds
var _idleSecondsCounter = 0;
var deviceType = "";
document.onclick = function () {
_idleSecondsCounter = 0;
};
//document.onmousemove = function () {
// _idleSecondsCounter = 0;
//};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime()
{
// create local user model
Ext.define('LocalUser', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: "id" },
{ name: "username", type: "string" },
{ name: "firstname", type: "string" },
{ name: "lastname", type: "string" },
{ name: "globalmessage", type: "string" },
{ name: "employeemessage", type: "string" },
{ name: "devicetype", type: "string" }
],
proxy: {
type: 'localstorage',
id: 'local-user'
}
}
});
var store = Ext.create('Ext.data.Store', {
model: 'LocalUser'
});
store.load();
var storageCount = store.getAllCount();
if (storageCount > 0)
{
//console.log(storageCount + " users found");
var userObject = store.getAt(storageCount - 1);
deviceType = userObject.get("devicetype");
//console.log("device type found by shared: " + deviceType);
}
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT)
{
if (deviceType == "terminal")
{
location.href = plano.Base.ResolveUrl('~/Account/TerminalLogout');
} else
{
location.href = plano.Base.ResolveUrl('~/Account/Logout');
}
}
}
</script>

Related

how to pass mxgraph generated xml to Action of controller?

I have started a project using asp.net mvc5 and then downloaded the mxGraph project from its original source of github https://github.com/jgraph/mxgraph
I have loaded mxgraph www folder and also src folder in my mvc project and edited my Index.cshtml file as below
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><!
[endif]-->
<!DOCTYPE html>
<html>
<head>
<title>Grapheditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" type="text/css" href="/styles/grapheditor.css">
<script type="text/javascript">
var urlParams = (function(url)
{
var result = new Object();
var idx = url.lastIndexOf('?');
if (idx > 0)
{
var params = url.substring(idx + 1).split('&');
for (var i = 0; i < params.length; i++)
{
idx = params[i].indexOf('=');
if (idx > 0)
{
result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
}
}
}
return result;
})(window.location.href);
mxLoadResources = false;
</script>
<script type="text/javascript" src="/js/Init.js"></script>
<script type="text/javascript" src="/deflate/pako.min.js"></script>
<script type="text/javascript" src="/deflate/base64.js"></script>
<script type="text/javascript" src="/jscolor/jscolor.js"></script>
<script type="text/javascript" src="/sanitizer/sanitizer.min.js"></script>
<script type="text/javascript" src="/src/js/mxClient.js"></script>
<script type="text/javascript" src="/js/EditorUi.js"></script>
<script type="text/javascript" src="/js/Editor.js"></script>
<script type="text/javascript" src="/js/Sidebar.js"></script>
<script type="text/javascript" src="/js/Graph.js"></script>
<script type="text/javascript" src="/js/Format.js"></script>
<script type="text/javascript" src="/js/Shapes.js"></script>
<script type="text/javascript" src="/js/Actions.js"></script>
<script type="text/javascript" src="/js/Menus.js"></script>
<script type="text/javascript" src="/js/Toolbar.js"></script>
<script type="text/javascript" src="/js/Dialogs.js"></script>
</head>
<body class="geEditor">
<script type="text/javascript">
(function() {
var editorUiInit = EditorUi.prototype.init;
EditorUi.prototype.init = function() {
editorUiInit.apply(this, arguments);
this.actions.get('export').setEnabled(false);
if (!Editor.useLocalStorage)
{
mxUtils.post(OPEN_URL, '', mxUtils.bind(this, function(req) {
var enabled = req.getStatus() != 404;
this.actions.get('open').setEnabled(enabled || Graph.fileSupport);
this.actions.get('import').setEnabled(enabled || Graph.fileSupport);
this.actions.get('save').setEnabled(enabled);
this.actions.get('saveAs').setEnabled(enabled);
this.actions.get('export').setEnabled(enabled);
}));
}
};
mxResources.loadDefaultBundle = false;
var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) || mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage);
mxUtils.getAll([bundle, /*STYLE_PATH +*/ '/styles/default.xml'], function(xhr) {
mxResources.parse(xhr[0].getText());
var themes = new Object();
themes[Graph.prototype.defaultThemeName] = xhr[1].getDocumentElement();
new EditorUi(new Editor(urlParams['chrome'] == '0', themes));
}, function() {
document.body.innerHTML = '<center style="margin-top:10%;">Error loading resource files. Please check browser console.</center>';
});
})();
</script>
</body>
</html>
this page loads properly.
and my init.js is as below:
// URLs for save and export
window.EXPORT_URL = window.EXPORT_URL || '/export';
window.SAVE_URL = window.SAVE_URL || 'save';
window.OPEN_URL = window.OPEN_URL || '/open.html';
window.RESOURCES_PATH = window.RESOURCES_PATH || '/resources';
window.RESOURCE_BASE = window.RESOURCE_BASE || window.RESOURCES_PATH + '/grapheditor';
window.STENCIL_PATH = window.STENCIL_PATH || '/stencils';
window.IMAGE_PATH = window.IMAGE_PATH || '/images';
window.STYLE_PATH = window.STYLE_PATH || '/styles';
window.CSS_PATH = window.CSS_PATH || '/styles';
window.OPEN_FORM = window.OPEN_FORM || '/open.html';
window.mxBasePath = window.mxBasePath || '/src';
window.mxLanguage = window.mxLanguage || urlParams['lang'];
window.mxLanguages = window.mxLanguages || ['de'];
and now i want to pass the generated xml to my Action after drawing diagram and click on File/Save.
Thanks for Reply. I found solution of my mean.
#{
Layout = null;
}
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->
<!DOCTYPE html>
<html>
<head>
<!--head is as past and jquery added-->
//previous repeated code collapsed for brevity
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
</head>
<body class="geEditor">
<script type="text/javascript">
// Extends EditorUi to update I/O action states based on availability of backend
(function () {
var editorUiInit = EditorUi.prototype.init;
EditorUi.prototype.init = function () {
editorUiInit.apply(this, arguments);
this.actions.get('export').setEnabled(false);
//previous repeated code collapsed for brevity
this.editor.setFilename('doc1.xml');
//save editorUi object
var editorUI = this;
//this part shal be inserted
//override EditorUi.saveFile function for customization
this.save = saveXml;
function saveXml() {
if (editorUI.editor.graph.isEditing()) {
editorUI.editor.graph.stopEditing();
}
var xml = mxUtils.getXml(editorUI.editor.getGraphXml());
//xml = encodeURIComponent(xml);
if (xml.length < MAX_REQUEST_SIZE) {
$.ajax({
type: "POST",
url: "home/save",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'xml': xml }),
success: function (response) {
//alert(response.message);
},
error: function (ex) {
alert(ex.message);
}
});
}
else {
mxUtils.alert(mxResources.get('drawingTooLarge'));
mxUtils.popup(xml);
return;
}
};
//reset onload open function
this.open = defaultOpen;
function defaultOpen() {};
};
})();
</script>
</body>
</html>

In PWA, Add to Homescreen Popoup show everytime when website is open

I have added PWA in my previously created asp.net MVC web application. Now I want that Add to homescreen Popup open every time when application open. I have attached my code for adding pwa in Website.
1) code of my AdminLayout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - PULSE</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<meta name="description" content="PMS System">
<meta name="author" content="Ashish Durve">
#{ Html.RenderPartial("GoogleAnalytics"); }
<!-- Add to home screen for Safari on iOS -->
#*<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Pulse">
<link rel="apple-touch-icon" href="images/icons/icon-152x152.png">*#
#Styles.Render("~/Content/css")
<link href="../Content/bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<link href="../Content/vendors/easypiechart/jquery.easy-pie-chart.css" rel="stylesheet" media="screen">
<link href="~/Content/assets/login_home.css" rel="stylesheet" />
#*Old Fontawsome 4.4.0 reference for old icons which are not included in new fontawsome 5.0.10*#
<link href="../../Content/bootstrap/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
#* New fontawsome 5.0.10 reference*#
<link href="../../Content/assets/fontawesome-all.css" rel="stylesheet" type="text/css" />
<link rel="manifest" href="~/manifest.json"> #*code for pwa manifest*#
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="../Content/vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<script src="../../Content/vendors/jquery-1.9.1.min.js"></script>
<script src="../../Content/bootstrap/js/popper.min.js"></script>
<script src="../../Content/bootstrap/js/bootstrap.min.js"></script>
<script src="../../Content/assets/bootstrap-material-design.js"></script>
<!--/.fluid-container-->
#*<script src="../../Content/vendors/jquery-1.9.1.min.js"></script>
<script src="../../Content/bootstrap/js/bootstrap.min.js"></script>*#
<script src="../../Content/vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="../../Content/assets/scripts.js"></script>
<script src="../../Content/vendors/bootstrap-wysihtml5/lib/js/wysihtml5-0.3.0.js"></script>
<script src="../../Content/assets/rhinoslider-1.05.min.js"></script>
<script src="../../Content/assets/mousewheel.js"></script>
<script src="../../Content/assets/easing.js"></script>
<!-- Material Design fonts -->
<!--<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">-->
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Bootstrap Material Design -->
<link href="../../Content/assets/bootstrap-material-design.css" rel="stylesheet">
<link href="../../Content/assets/ripples.min.css" rel="stylesheet">
#*<link href="../../Content/assets/addtohomescreen.css" rel="stylesheet" />
<script src="../../Content/assets/addtohomescreen.min.js"></script>
<script src="../../Content/assets/addtohomescreen.js"></script>*#
<script src="../../Content/assets/material.js"></script>
#*<script src="../../Content/assets/bootstrap-material-design.js"></script>*#
<script src="../../Content/assets/ripples.min.js"></script>
<!--iphone PWA AppIcon Reference -->
<link rel="apple-touch-icon" href="touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-retina.png">
<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<!--End-->
<!--iphone PWA Splash Screen Reference -->
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-startup-image" href="/launch.png">
<!-- iPhone X (1125px x 2436px) -->
<link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3)" href="/apple-launch-1125x2436.png">
<!-- iPhone 8, 7, 6s, 6 (750px x 1334px) -->
<link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-750x1334.png">
<!-- iPhone 8 Plus, 7 Plus, 6s Plus, 6 Plus (1242px x 2208px) -->
<link rel="apple-touch-startup-image" media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3)" href="/apple-launch-1242x2208.png">
<!-- iPhone 5 (640px x 1136px) -->
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-640x1136.png">
<!-- iPad Mini, Air (1536px x 2048px) -->
<link rel="apple-touch-startup-image" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-1536x2048.png">
<!-- iPad Pro 10.5" (1668px x 2224px) -->
<link rel="apple-touch-startup-image" media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-1668x2224.png">
<!-- iPad Pro 12.9" (2048px x 2732px) -->
<link rel="apple-touch-startup-image" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-2048x2732.png">
<!--End-->
<script>
$.material.init();
</script>
#*<script>
$(document).ready(function () { $('body').bootstrapMaterialDesign(); });
</script>*#
<style>
##media all and (display-mode: standalone) {
body {
background-color: yellow;
}
}
</style>
</head>
<body class="pattern">
<div class="container-fluid">
<div class="row-fluid">
<!--/span-->
#RenderBody()
</div>
<footer>
</footer>
</div>
<script type="text/javascript">
var err = 0;
var handleError;
$(document).ready(function () {
//add to home screen code
window.addEventListener("beforeinstallprompt", function (e) {
// log the platforms provided as options in an install prompt
//console.log(e.platforms); // e.g., ["web", "android", "windows"]
e.userChoice.then(function (outcome) {
//console.log(outcome); // either "accepted" or "dismissed"
}, handleError);
});
//window.addEventListener('appinstalled', (evt) => {
// app.logEvent('a2hs', 'installed');
//});
/////////////////////////////////
// //uncomment the below code
// let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
deferredPrompt.prompt();
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
//console.log('User accepted the A2HS prompt');
} else {
//console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
window.addEventListener('appinstalled', (evt) => {
app.logEvent('a2hs', 'installed');
});
//// notify the user your app can be installed
// window.addEventListener('beforeinstallprompt', (e) => {
// e.preventDefault();
// deferredPrompt = e;
// // Update UI notify the user they can add to home screen
// btnAdd.style.display = 'block';
// });
//////Show prompt
//btnAdd.addEventListener('click', (e) => {
// // hide our user interface that shows our A2HS button
// btnAdd.style.display = 'none';
// // Show the prompt
// deferredPrompt.prompt();
// // Wait for the user to respond to the prompt
// deferredPrompt.userChoice
// .then((choiceResult) => {
// if (choiceResult.outcome === 'accepted') {
// console.log('User accepted the A2HS prompt');
// } else {
// console.log('User dismissed the A2HS prompt');
// }
// deferredPrompt = null;
// });
//});
$('#slider').rhinoslider({
controlsPlayPause: false,
showControls: 'always',
showBullets: 'always',
controlsMousewheel: false,
prevText: 'Back',
nextText:'Proceed',
slidePrevDirection: 'toRight',
slideNextDirection: 'toLeft',
cycled: 'false',
controlsKeyboard: 'false'
});
$(".rhino-prev").hide();
$('.rhino-next').after('<a class="form-submit" href="javascript:void(0);" >Proceed</a>');
$(".rhino-next").hide();
var info = ["PERSONAL DETAILS","ACCOUNT DETAILS","ORGANIZATION DETAILS"];
var images = ["../../Content/Images/personal-details-icon.png", "../../Content/Images/account-details.png", "../../Content/Images/contact-details.png"];
$('.rhino-bullet').each(function(index){
$(this).html('<p style="margin: 0pt; font-size: 13px; font-weight: bold;"><img src="./img/'+
images[index]+'"></p><p class="bullet-desc">'+info[index]+'</p></a>');
});
});
$('body').on('click', '.form-submit', function(){
// $('.form-submit').on("click",function(){
$('.form-error').html("");
err = 0;
var current_tab = $('#slider').find('.rhino-active').attr("id");
switch(current_tab){
case 'rhino-item0':
step1_validation();
break;
case 'rhino-item1':
step2_validation();
break;
case 'rhino-item2':
step3_validation();
if (err == 0) {
//alert(err);
$("#freeRegister").submit();
}
break;
}
});
var step1_validation = function(){
//var err = 0;
if($('#fname').val() == ''){
$('#fname').parent().find('.form-error').html("Please enter first name.");
err++;
}
if($('#lname').val() == ''){
$('#lname').parent().find('.form-error').html("Please enter last name.");
err++;
}
if ($('#mobile').val() == '') {
$('#mobile').parent().find('.form-error').html("Please enter mobile phone number.");
err++;
}
else {
var x = $('#mobile').val();
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!x.match(phoneno)) {
$('#mobile').parent().find('.form-error').html("Please enter valid mobile phone number.");
err++;
}
}
if(err == 0){
$(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
$(".rhino-next").show();
$('.form-submit').hide();
$('.rhino-next').trigger('click');
}else{
$(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
}
};
var step2_validation = function(){
//var err = 0;
if ($('#username').val() == '') {
$('#username').parent().find('.form-error').html("Please enter UserName/Email.");
err++;
}
else {
var x = $('#username').val();
var userName = /^([\w-]+(?:\.[\w-]+)*)##((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!x.match(userName)) {
$('#username').parent().find('.form-error').html("Please enter valid Email.");
err++;
}
if (!checkUserName(x)) {
$('#username').parent().find('.form-error').html("This user is already registered with us.");
err++;
}
}
if($('#pass').val() == ''){
$('#pass').parent().find('.form-error').html("Please enter password");
err++;
}
if ($('#cpass').val() == '') {
$('#cpass').parent().find('.form-error').html("Please enter confirm password.");
err++;
}
else {
var pass = $('#pass').val();
var cpass = $('#cpass').val();
if (pass != cpass) {
$('#cpass').parent().find('.form-error').html("Confirm password should match password field.");
err++;
}
}
if(err == 0){
$(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
$(".rhino-next").show();
$('.form-submit').hide();
$('.rhino-next').trigger('click');
}else{
$(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
}
};
var step3_validation = function(){
//var err = 0;
if($('#orgName').val() == ''){
$('#orgName').parent().find('.form-error').html("Please enter organization name.");
err++;
}
if(err == 0){
$(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
$(".rhino-next").show();
$('.form-submit').hide();
$('.rhino-next').trigger('click');
}else{
$(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
}
};
function checkUserName(userName) {
valid = false;
url = "../Account/VerifyUserName?userName=" + userName;
$.ajax(
{
url: url,
type: "GET",
async: false,
success: function (data, textStatus, jqXHR) {
if (data == "0") {
valid = false;
}
else {
valid = true;
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed to get data. Please contact support team.")
return false;
}
});
return valid;
}
</script>
#*<div class="overlay"></div>*#
</body>
</html>
<script>
// code for service worker of pwa start
if ('serviceWorker' in navigator) {
console.log("Will the service worker register?");
navigator.serviceWorker.register('../serviceWorker.js')
.then(function (reg) {
console.log(reg);
console.log("Yes, it did.");
}).catch(function (err) {
console.log("No it didn't. This happened: ", err)
});
}
// code for service worker of pwa end
</script>
<script>
var deferredPrompt;
window.addEventListener('beforeinstallprompt', function (e) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
showAddToHomeScreen();
});
</script>
2) serviseworker.js
(function () {
'use strict';
var version = 'v1.0::CacheFirstSafe';
var offlineUrl = "../Controller/Account/Login.cshtml"; // <-- Offline/Index.cshtml
var urlsToCache = ['/', offlineUrl]; // <-- Add more URLs you would like to cache.
// Store core files in a cache (including a page to display when offline)
function updateStaticCache() {
return caches.open(version)
.then(function (cache) {
return cache.addAll(urlsToCache);
});
}
function addToCache(request, response) {
if (!response.ok && response.type !== 'opaque')
return;
var copy = response.clone();
caches.open(version)
.then(function (cache) {
cache.put(request, copy);
});
}
function serveOfflineImage(request) {
if (request.headers.get('Accept').indexOf('image') !== -1) {
return new Response('<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg"><title id="offline-title">Offline</title><g fill="none" fill-rule="evenodd"><path fill="#D8D8D8" d="M0 0h400v300H0z"/><text fill="#9B9B9B" font-family="Helvetica Neue,Arial,Helvetica,sans-serif" font-size="72" font-weight="bold"><tspan x="93" y="172">offline</tspan></text></g></svg>', { headers: { 'Content-Type': 'image/svg+xml' } });
}
}
self.addEventListener('install', function (event) {
event.waitUntil(updateStaticCache());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then(function (keys) {
// Remove caches whose name is no longer valid
return Promise.all(keys
.filter(function (key) {
return key.indexOf(version) !== 0;
})
.map(function (key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', function (event) {
var request = event.request;
// Always fetch non-GET requests from the network
if (request.method !== 'GET' || request.url.match('../Controller/Account/Login.cshtml')) {
event.respondWith(
fetch(request)
.catch(function () {
return caches.match(offlineUrl);
})
);
return;
}
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
event.respondWith(
fetch(request)
.then(function (response) {
// Stash a copy of this page in the cache
addToCache(request, response);
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || caches.match(offlineUrl);
});
})
);
return;
}
// cache first for fingerprinted resources
if (request.url.match(/(\?|&)v=/ig)) {
event.respondWith(
caches.match(request)
.then(function (response) {
return response || fetch(request)
.then(function (response) {
addToCache(request, response);
return response || serveOfflineImage(request);
})
.catch(function () {
return serveOfflineImage(request);
});
})
);
return;
}
// network first for non-fingerprinted resources
event.respondWith(
fetch(request)
.then(function (response) {
// Stash a copy of this page in the cache
addToCache(request, response);
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || serveOfflineImage(request);
})
.catch(function () {
return serveOfflineImage(request);
});
})
);
});
})();
4) Manifest.json
{
"name": "Pulse",
"short_name": "Pulse",
"description": "Pulse Progressive Web Application",
"icons": [
{
"src": "../../Content/images/icon16x16.png",
"sizes": "16x16",
"type": "image/png",
"density": 0.25
},
{
"src": "../../Content/images/icon20x20.png",
"sizes": "20x20",
"type": "image/png",
"density": 0.5
},
{
"src": "../../Content/images/icon32x32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "../../Content/images/icon36x36.png",
"sizes": "36x36",
"type": "image/png",
"density": 0.75
},
{
"src": "../../Content/images/icon40x40.png",
"sizes": "40x40",
"type": "image/png"
},
{
"src": "../../Content/images/icon48x48.png",
"sizes": "48x48",
"type": "image/png",
"density": 1.0
},
{
"src": "../../Content/images/icon60x60.png",
"sizes": "60x60",
"type": "image/png"
},
{
"src": "../../Content/images/icon64x64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "../../Content/images/icon72x72.png",
"sizes": "72x72",
"type": "image/png",
"density": 1.5
},
{
"src": "../../Content/images/icon88x88.png",
"sizes": "88x88",
"type": "image/png"
},
{
"src": "../../Content/images/icon96x96.png",
"sizes": "96x96",
"type": "image/png",
"density": 2.0
},
{
"src": "../../Content/images/icon128x128.png",
"sizes": "128x128",
"type": "image/png",
"density": 2.0
},
{
"src": "../../Content/images/icon144x144.png",
"sizes": "144x144",
"type": "image/png",
"density": 3.0
},
{
"src": "../../Content/images/icon172x172.png",
"sizes": "172x172",
"type": "image/png"
},
{
"src": "../../Content/images/icon192x192.png",
"sizes": "192x192",
"type": "image/png",
"density": 4.0
},
{
"src": "../../Content/images/icon196x196.png",
"sizes": "196x196",
"type": "image/png"
},
{
"src": "../../Content/images/icon256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "../../Content/images/icon512x512.png",
"sizes": "512x512",
"type": "image/png",
"density": 5.0
},
{
"src": "../../Content/images/icon1024x1024.png",
"sizes": "1024x1024",
"type": "image/png"
}
],
"display": "standalone",
"theme_color": "#536878",
"background_color": "#fff",
"start_url": "/"
}

How to draw line for real time flot?

Starting from here: How do I display a Json random number in a real-time Flot chart?, I managed to display a random number on a flot chart. The x axes is the current time's second. The problem I have is that now on my chart is shown only a point (current value). What I want is to display a real time line according to the values of the random number. How could I do this? I hope I made myself understood.
Here is my cod:
In C#:
if (method == "rnd")
{
//Current second
this.Page.Response.ContentType = "application/json1";
DateTime now = DateTime.Now;
int sec = now.Second;
Random rnd = new Random();
int nr = rnd.Next(1, 100); // creates a number between 1 and 99
var str = "{\"sec\":" + sec.ToString() + ",\"val\":" + nr.ToString() + "}";
var json2 = new JavaScriptSerializer().Serialize(str);
this.Page.Response.Write(json2);
}
My ASP page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MultiTrenduri.aspx.cs" Inherits="WebApplication2.MultiTrenduri" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/flot/jquery.flot.min.js"></script>
<script src="Scripts/flot/jquery.flot.time.js"></script>
<script src="Scripts/flot/jquery.flot.symbol.js"></script>
<script src="Scripts/flot/hashtable.js"></script>
<script src="Scripts/flot/jquery.flot.axislabels.js"></script>
<script src="Scripts/flot/jquery.numberformatter-1.2.3.min.js"></script>
<link href="Flot/examples.css" rel="stylesheet" />
<script type="text/javascript">
var sc = [], num = [];
function test2() {
$.ajax({
type: 'POST',
url: ('ajax.aspx?meth=') + "rnd",
contentType: 'application/json2; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
global: false,
timeout: 120000,
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(data);
$('#azi').html(obj.sec);
$('#nr').html(obj.val);
var sc = [], num = [];
sc.push(obj.sec);
num.push(obj.val);
data = [[[sc, num]]];
//var afis = [[[data]]];
//$('#afs').text(afis.join(" * "));
//show the data in a list in body
var items = [];
$.each(data, function (key, val1) {
items.push("<li><a href=#'" + key + "'>" + val1 + "</a></li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
//START: PLOT IN TIMP REAL
$(function () {
var plot = $.plot("#placeholder", data,
{
series: {
shadowSize: 0 // Drawing is faster without shadows
},
points: { show: true },
line: { show: true },
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: true
}
});
// plot.setData(data); //to reset data
// plot.draw(); //to redraw chart
});
// plot.draw();
//END: PLOT IN TIMP REAL
},
error: function (jqXHR, textStatus, errorThrown) {
window.alert(errorThrown);
}
});
}
window.setInterval(test2, 1000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="azi"></div>
<div id="nr"></div>
<div class="demo-container">
<div id="placeholder" class="demo-placeholder">
</div>
</div>
</div>
</form>
</body>
</html>
Maybe is someone which needs to do the same. This is how I managed to do it.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/flot/jquery.flot.min.js"></script>
<script src="Scripts/flot/jquery.flot.time.js"></script>
<script src="Scripts/flot/jquery.flot.symbol.js"></script>
<script src="Scripts/flot/hashtable.js"></script>
<script src="Scripts/flot/jquery.flot.axislabels.js"></script>
<script src="Scripts/flot/jquery.numberformatter-1.2.3.min.js"></script>
<link href="Flot/examples.css" rel="stylesheet" />
<%-- Library for TOOLTIP:--%>
<script src="Scripts/flot/jquery.flot.crosshair.js"></script>
<!-- CSS -->
<%--<style type="text/css">
#placeholder {
width: 1000px;
height: 500px;
text-align: center;
margin: 0 auto;
}
</style>--%>
<%-- <link href="Flot/examples.css" rel="stylesheet" />--%>
<%-- <script src="Scripts/jquery-1.4.1.js"></script>
<script src="Scripts/flot/jquery.flot.js"></script>--%>
<script type="text/javascript">
var sc = [], num = [];
var data = [];
var dataset;
var totalPoints = 100;
var updateInterval=30 ;
var now = new Date().getTime();
var t;
var multipleCalls, multCalls;
var input = document.getElementById('input');
var st;
/* window.onload = function f1() {
document.getElementById('updateInterval').value = 90;
}
function f2() {
// document.getElementById('up2').value = document.getElementById('up1').value
var updateInterval = document.getElementById('updateInterval').value;
// window.alert(updateInterval);
}*/
$(function () {
function test2() {
$.ajax({
type: 'GET',
url: ('ajax.aspx?meth=') + "rnd",
contentType: 'application/json2; charset=utf-8',
dataType: 'json',
//async: true,
//cache: false,
//global: false,
// timeout: 120000,
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(data);
$('#azi').html(obj.sec);
$('#nr').html(obj.val);
t = obj.val;
},
error: function (jqXHR, textStatus, errorThrown) {
window.alert(errorThrown);
}
});
}
function apel() {
test2();
$('#fn').html(t);
updateInterval = document.getElementById('updateInterval').value;
}
function GetData() {
data.shift();
data.slice(1);
while (data.length < totalPoints) {
// var y = Math.random() * 100;
var y = t;
var temp = [now += updateInterval, y];
data.push(temp);
}
}
$("#up").val(updateInterval).change(function () {
var vv = $(this).val();
if (vv && !isNaN(+vv)) {
updateInterval = +vv;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var options = {
series: {
lines: {
show: true,
lineWidth: 1.2,
fill: false
}
},
xaxis: {
mode: "time",
tickSize: [2, "second"],
tickFormatter: function (v, axis) {
var date = new Date(v);
if (date.getSeconds() % 5 == 0) {
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
var w = hours + ":" + minutes + ":" + seconds;
return w;
} else {
return "";
}
},
axisLabel: "Time",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10
},
grid: {
hoverable: true,
clickable: true
},
yaxis: {
min: 0,
max: 100,
tickSize: 5,
tickFormatter: function (v, axis) {
if (v % 10 == 0) {
return v + "%";
} else {
return "";
}
},
axisLabel: "CPU loading",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 6
},
legend: {
labelBoxBorderColor: "#fff"
}
};
//START TOOLTIP
/* $("#placeholder").bind("plothover", function (event, pos, item) {
if ($("#enablePosition:checked").length > 0) {
var str = "(" + pos.x.toFixed(2) + ", " + pos.y.toFixed(2) + ")";
$("#hoverdata").text(str);
}
if ($("#enableTooltip:checked").length > 0) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
$("#tooltip").html(item.series.label + " of " + x + " = " + y)
.css({ top: item.pageY + 5, left: item.pageX + 5 })
.fadeIn(200);
} else {
$("#tooltip").hide();
}
}
});
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label);
plot.highlight(item.series, item.datapoint);
}
});
*/
//END TOOLTIP
st = $(document).ready(function f1() {
test2();
GetData();
dataset = [
{ label: "CPU", data: data }
];
$.plot($("#placeholder"), dataset, options);
function stop() {
//window.alert("Stop");
//multipleCalls.clearTimeout();
window.clearTimeout(updateInterval);
}
function update() {
test2();
GetData();
$.plot($("#placeholder"), dataset, options)
multipleCalls = setTimeout(update, updateInterval);
multCalls = multipleCalls;
}
update();
});
});
</script>
</head>
<body>
//Stops the graph
<button onclick="clearInterval(multipleCalls)">Stop</button>
<div id="header">
<div id="azi"></div>
<div id="nr"></div>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>Time between updates: <input id="up" type="text" value="" style="text-align: right; width:5em"/> milliseconds</p>
</div>
</body>
</html>

JqGrid not Showing Grid in ASP.NET MVC3

View :
#{
ViewBag.Title = "TestGrid";
}
<link href="#Url.Content("~/Content/JqGrid/jquery-ui-jqgrid.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/JqGrid/jquery-1.5.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/JqGrid/jquery-ui-1.8.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/JqGrid/jquery-ui.multiselect.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/JqGrid/jquery.tmpl.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/JqGrid/jquery.jqGrid.locale-en-4.1.2.js")"
type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/JqGrid/jquery.jqGrid-4.1.2.min.js")" type="text/javascript"></script>
<h2>
TestGrid</h2>
<h2>
My Grid Data</h2>
<table id="list">
</table>
<div id="pager">
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: 'Grid/GridData',
datatype: 'json',
colNames: ['COM_NAME', 'COM_CODE', 'DELV_UNITS', 'LOT_SIZE', 'TICK_SIZE', 'TICK_VALUE'],
colModel: [
{ name: 'COM_NAME', index: 'COM_NAME', width: 90 },
{ name: 'COM_CODE', index: 'COM_CODE', width: 100 },
{ name: 'DELV_UNITS', index: 'DELV_UNITS', width: 80, align: "right" },
{ name: 'LOT_SIZE', index: 'LOT_SIZE', width: 80, align: "right" },
{ name: 'TICK_SIZE', index: 'TICK_SIZE', width: 80, align: "right" },
{ name: 'TICK_VALUE', index: 'TICK_VALUE', width: 150, sortable: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager',
viewrecords: true,
jsonReader: {
root: "rows",
page: "page",
cell: "cell"
},
caption: "JSON Example"
});
});
jQuery("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
</script>
Controller :
public ActionResult GridData(string sidx = "", string sord = "", int page = 1, int rows = 10)
{
TestGridModel tstGrid = new TestGridModel();
tstGrid.listArr = new List<CommodityReport>();
string conn = ConfigurationManager.ConnectionStrings["DbConnnectionString"].ConnectionString;
ReportDAL rptDal = new ReportDAL();
DataTable dt = rptDal.GetCommodity(conn, "");
//List<string[]> row = new List<string[]>();
List<Cell> row = new List<Cell>();
int i = 0;
foreach (DataRow item in dt.Rows)
{
row.Add(new Cell { cell = dt.Rows[i].ItemArray.Select(x => x.ToString()).ToArray() });
i++;
}
var jsonData = new
{
total = 1, // we'll implement later
page = page,
records = 3, // implement later
rows = row.ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Result :
{"total":1,"page":1,"records":3,"rows":[{"cell":
["WHEAT","WHEAT","1","1.0000","1","100.000000"]},{"cell":["SL10","SILVER","1","1.0000","1","10.000000"]},{"cell":["CL10","CRUDE10","1","0.0100","1","10.000000"]},{"cell":["SL100","SL100OZ","1","0.0010","100","100.000000"]},{"cell":["TOLAGOLD","TOLAGOLD","1","1.0000","10","1.000000"]},{"cell":["JPYUSD","JPYUSD","1","0.0100","10000","10000.000000"]},{"cell":["GOKILO","GOLDKILO","1","1.0000","1","103.260000"]},{"cell":["TG100","TGOLD100","1","1.0000","100","100.000000"]},{"cell":
["TG50","TGOLD50","1","1.0000","50","50.000000"]},{"cell":["RBDPO","PALMOLEIN","1","1.0000","1","669.810000"]},{"cell":["GO","GOLD","1","1.0000","10","10.000000"]},{"cell":["GOD","GOLDOCTDEC","1","1.0000","1","1.000000"]},{"cell":["GSDJ","GOSPDECJAN","1","1.0000","1","1.000000"]},{"cell":["GSMA","GOSPMARAPR","1","1.0000","1","1.000000"]},{"cell":["RI6","RICEIRRI6","1","1.0000","1","250.000000"]},{"cell":["GSGP","GOSPAUGSEP","1","1.0000","1","10.000000"]},{"cell":["MGOLD","MINIGOLD","10","1.0000","10","1.000000"]},{"cell":["BCO","BRENTCRUDE","1","1.0000","1","1.000000"]},{"cell":["PT","PLATINUM","1","1.0000","1","1.000000"]},{"cell":["GSLG","GOSPJULAUG","1","1.0000","1","10.000000"]},{"cell":["PKRUSD","PKRUSD","1000","0.0100","1","10.000000"]},{"cell":["GO1KG","GOLD1KG","1","1.0000","1","103.260000"]},{"cell":["K3M","KIBOR3M","1","0.0100","1","2500.000000"]},{"cell":["TTGOLD","TTGOLD","10","1.0000","1","10.000000"]},{"cell":["CRUDEOIL","CRUDEOIL","1","0.0100","100","100.000000"]},{"cell":["GO100","GO100OZ","1","0.1000","100","100.000000"]},{"cell":["IRRI6W","IRRI6W","1","1.0000","1","250.000000"]},{"cell":["SL500","SL500OZ","1","0.0010","500","500.000000"]},{"cell":["GO1","GO1OZ","1","0.1000","1","1.000000"]},{"cell":["WTI100","WTI100","1","0.0100","100","100.000000"]},{"cell":["CL100","CRUDE100","1","0.0100","1","100.000000"]},{"cell":["EURUSD","EURUSD","1","0.0001","10000","10000.000000"]},{"cell":["GBPUSD","GBPUSD","1","0.0001","10000","10000.000000"]},{"cell":["USDJPY","USDJPY","1","0.0100","10000","10000.000000"]},{"cell":["TGOLD","TGOLD","1","1.0000","10","1.000000"]},{"cell":["SUGAR","SUGAR","1","0.0100","1","10000.000000"]},{"cell":["USCOTTON","USCOTTON","1","0.0100","1","50.000000"]},{"cell":["GO10","GO10OZ","1","0.1000","10","10.000000"]},{"cell":["SLV10","SL10","1","0.0010","10","10.000000"]},{"cell":
["ICT","ICOTTON","1","0.0100","1","50.000000"]},{"cell":["MTGOLD","MTOLAGOLD","1","1.0000","10000","0.001000"]},{"cell":["COPPER","COPPER","1","0.0001","1000","1000.000000"]},{"cell":["BRENT10","BRENT10","1","0.0100","1","10.000000"]},{"cell":["BRENT100","BRENT100","1","0.0100","1","100.000000"]}]}
problem is when my controller returns the Json it simply show the Json on Webpage instead of grid. can any help me whats the problem ?

How to add auto complete json for dynamically generated textboxes in asp.net

I am trying to generate dynamic html textboxes in my aspx page and on these textboxes i want to add the value using autocomplete facility. I try my best to do so. I try almost every single question's answer of stackoverflow. But nothing is working here my script which generate new textbox dynmacally
<script type="text/javascript">
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
// newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
// '<input type="text" name="textbox' + counter +
// '" id="textbox' + counter + '" value="" class="auto">');
newTextBoxDiv.after().html('<div class="fields-left"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter+1 + '" class="auto"/> </div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
Html code
<div id="TextBoxDiv1" class="fields" >
<div id="TextBoxesGroup">
</div>
</div>
<input type='button' value='Add Button' id='addButton'/>
<input type='button' value='Remove Button' id='removeButton'/>
</div>
and I am trying this json code for fetching data for very first textbox that generate automatically. First I think for write this script for everytextbox which generate dynamically but this process will be so lengthy and wrong way to do this thing. But this is not working for me
<script type="text/javascript">
$(document).ready(function () {
SearchText2();
});
function SearchText2() {
$("#textbox2").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById('textbox2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
Please experts tell me why this json is working for me
Thanks
Please use following code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="Web.Home" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var counter = 2;
$(document).ready(function () {
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var $wrap = $('#TextBoxesGroup');
var dynamichtml = '<div class="fields-left" id="divleft_' + counter + '"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right" id="divright_' + counter + '"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div>';
$wrap.append(dynamichtml);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxesGroup").find("#divleft_" + counter).remove();
$("#TextBoxesGroup").find("#divright_" + counter).remove();
});
$(".auto").live("focus", function () {
$(this).autocomplete({
minLength: 2,
source: function (request, response) {
var textval = request.term; // $(this).val();
$.ajax({
url: "Home.aspx/GetAutoCompleteData", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ code: textval }),
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}, select: function (event, ui) {
return false;
}
});
});
});
</script>
<style type="text/css">
.ui-menu { width: 150px; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="TextBoxDiv1" class="fields" >
<div id="TextBoxesGroup">
</div>
</div>
<input type='button' value='Add Button' id='addButton'/>
<input type='button' value='Remove Button' id='removeButton'/>
</div>
</form>
</body>
</html>
In .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace Web
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
[WebMethod]
public static List<string> GetAutoCompleteData(string code)
{
List<string> list = new List<string>();
list.Add("delhi");
list.Add("noida");
list.Add("gurgaon");
return list.Where(i => i.StartsWith(code)).ToList();
}
}
}
Please add js file as below
I would suggest you to use global variable say data to store the json response retirned for autocomplete.
and then use the same data to bind autocomplete after appending the contents.
$('#newTextBoxDiv input').autocomplete(data);

Categories

Resources