Call ASMX web service from Javascript in asp.net - javascript

I have built an asmx web service that reads from a local sql database which I want to connect to my web application. I have already added a service reference, the only issue is I do not know how to call the web service in my web application directly.
Here is part of my asmx web service:
<%# WebService Language="C#" Class="PostWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class PostWebService : System.Web.Services.WebService {
//method to get heart rates from sql database
[WebMethod]
public List<int> GetHeartRates() {
var heartRate = new List<int>();
try
{
using (SqlConnection connection = new SqlConnection(#"Data Source = (local); Initial Catalog = RatesDB; Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(" select HeartRate from Rates", connection))
{
connection.Open();
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
heartRate.Add((int)rdr[0]);
}
rdr.Close();
connection.Close();
}
}
catch
{
}
return heartRate;
}
Here is part of my .aspx web page
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['gauge']
});
d3.csv("brT16.csv", function (rrdata) {
d3.csv("hrT16.csv", function (hrdata) {
for (var i = 0; i < rrdata.length; i++) {
for (var j = 0; j < hrdata.length; j++) {
console.log(rrdata[i]);
console.log(hrdata[j]);
}
}
count = 0;
count2 = 0;
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// respiration gauge
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['RR', 0],
//['Heart Rate', 0],
]);
var options = {
width: 600,
height: 250,
redFrom: 35,
redTo: 55,
yellowFrom: 25,
yellowTo: 35,
minorTicks: 5,
max: 50,
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
setInterval(function () {
data.setValue(0, 1, parseInt(rrdata[count][0]));
chart.draw(data, options);
count++;
}, 1000);
I want to call the web service directly so that it reads from the sql database instead of the csv. Any tips in the right direction would be appreciated.

When adding Reference to web-service make sure you are clicking advance button and adding web Reference(Advance -> Add Web Reference -> paste Url -> Add reference). You should be able to call web service methods after that.

Related

How can I get the callback data with WebView2

I'm building a WPF application and try to get the ajax callback data with the WebView2 control.
WebApplication is a simple Login View, and login method code like this:
$("#btn").click(function () {
$.post("loginHandler.ashx",
{
name: $("#name").val(),
pwd: $("#pwd").val()
},
function (data, status) {
var r=JSON.parse(data)
alert(r.result);
});
});
the XAML code in wpf is:
<wv2:WebView2 Name="webView" Source="http://localhost:44372/login.html" />
Now I use the CoreWebView2_WebResourceResponseReceived to get the request and response information, but I can't get the data in the callback function...
After searching around for decent maybe I should use Javascript? Can JS catch another function's callback result?
Please give me some advise, I'm the first time use to controls...
(If WebView2 can't do this, may the CefSharp do that?)
Any assistance is appreciated, THX!
CoreWebView2.WebResourceResponseReceived is raised whenever the WebView2 gets an http(s) response back from a server and you can check the contents and headers for the response.
But if the content you're trying to obtain exists only in JavaScript you can use CoreWebView2.WebMessageReceived and window.chrome.webview.postMessage to send the content from script to your C#.
In script you'd do something along the lines of:
$("#btn").click(function () {
$.post("loginHandler.ashx",
{
name: $("#name").val(),
pwd: $("#pwd").val()
},
function (data, status) {
var r=JSON.parse(data)
// Send data to the host app
chrome.webview.postMessage(r);
});
});
And in your C# you'd hook up a WebMessageReceived event handler something like:
// During initialization after CoreWebView2 property is set
// and before you navigate the webview2 to the page that will
// post the data.
webView.CoreWebView2.WebMessageReceived += ReceiveLoginData;
// ...
}
void ReceiveLoginData(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
String loginDataAsJson = args.WebMessageAsJson();
// parse the JSON string into an object
// ...
}
You can see more example usage of WebMessageReceived and PostWebMessage in the WebView2 sample app.
Create a html folder in bin/debug/ path :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="demo">lkkkkkkkkkkkkkkkkkkkkkk</div>
<div id="demo1">uuuuuuuuuuuuuuuuuuuuuu</div>
<div id="demo2">pppppppppppppppppppppp</div>
<button onclick="me()">Click me</button>
<button onclick="sendThisItem('hidear')">Clickkkkkkkkkkkkkkkkkkk me</button>
<script>
function me() {
var me = "ddddddddd";
document.getElementById('demo1').style.color = 'yellow';
window.chrome.webview.postMessage('dellmaddddddddddddddddddd');
}
</script>
</body>
</html>
Now in Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Web.WebView2.Core;
namespace WindowsFormsAppWebview
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitwebView();
}
async void InitwebView()
{
await webView21.EnsureCoreWebView2Async(null);
webView21.CoreWebView2.Navigate(Path.Combine("file:", Application.StartupPath, #"html\", "index.html"));
webView21.WebMessageReceived += webView2_WebMessageReceived;
}
private void webView2_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs args)
{
label1.Text = args.TryGetWebMessageAsString();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "sssssssss";
//MessageBox.Show("hello world ");
webView21.CoreWebView2.ExecuteScriptAsync("document.getElementById('demo').style.color = 'red'");
}
}
}
You need to Create label1,button1 , webView21 in Form.
This line is importent:
webView21.WebMessageReceived += webView2_WebMessageReceived;

How to Call to a UI variable of JavaFX from javascript in WebEngine?

I'm working on an application that needs to read a local file and display it in WebView, based on user input (in ComboBox).
I'm trying to call to a variable in the JavaFX UI from JavaScript and it doesn't work.
I created a function called getMonthIndex() in the Java code that returns the input of the ComboBox and that the file should be received with the appropriate name.
I'm trying to import this function into the JavaScript code, and it doesn't seem to be included in the JavaScript code.
If you can explain to me how to get a parameter from the JavaFX UI and use it within the JavaScript code.
Thanks so much in advance for any help you can.
My Controller.java:
public class Controller {
ObservableList<String> months = FXCollections.observableArrayList
("Tishrei", "Cheshvan", "Kislev", "Tevet", "Shevat", "Adar",
"Nisan", "Iyar", "Sivan", "Tammuz", "Av", "Elul");
public ComboBox<String> month;
public WebView webView;
public String getMonthIndex() {
ReadOnlyIntegerProperty listIndex = month.getSelectionModel().selectedIndexProperty();
return String.format("%02d", listIndex.getValue());
}
public long linesCount(String scanFile) {
if (scanFile.length() < 80) {
return scanFile.length() / 15;
} else {
return scanFile.length() / 24;
}
}
#FXML
public void initialize() {
month.setItems(months);
webView.setContextMenuEnabled(false);
WebEngine webEngine = webView.getEngine();
Controller controller = new Controller();
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("app", controller);
month.setOnAction(event -> {
String loadFile = this.getClass().getResource("index.html").toString();
webEngine.load(loadFile);
});
}
}
My index.html (uploaded by WebEngine):
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="readTextFile()">
<div id="text">
</div>
<script type="text/javascript">
function readTextFile() {
var xhr, i, text, lines;
xhr = new XMLHttpRequest();
xhr.open('GET', app.getMonthIndex()+'.txt', true);
xhr.send(null);
xhr.onreadystatechange = function(){
text = xhr.responseText;
lines = text.split("\n");
var allText = "";
for(i = 0; i < lines.length; i++){
allText += lines[i]+"<br>";
}
document.getElementById("text").innerHTML = allText;
}
}
</script>
</body>
</html>
You’re creating a new instance of the Controller, which has no connection at all to the UI, and passing it to the web engine:
Controller controller = new Controller();
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("app", controller);
Instead, just pass the current instance:
// Controller controller = new Controller();
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("app", this);

how to pass array of markers from servlet to javascript [duplicate]

This question already has answers here:
How to let JavaScript use the variable from server side? [duplicate]
(2 answers)
Closed 7 years ago.
I want pass array of markes to javascript on jsp page to show them on google map.
In servlet I load array of markers from database, but I don't know how to pass them to javascript.
Thi is my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) `throws ServletException, IOException {
// TODO Auto-generated method stub`
PlaceDao placeDao = new PlaceDao();
ArrayList<Place> pList = new ArrayList<Place>();
try {
pList = placeDao.readData();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Marker marker = new Marker();
ArrayList<Marker> mList = new ArrayList<Marker>();
for (int i = 0; i < pList.size(); ++i)
{
marker.setLatitude(pList.get(i).getLatitude());
marker.setLongitude(pList.get(i).getLongitude());
mList.add(marker);
}
request.setAttribute("marker", mList);
request.getRequestDispatcher("pages/location.jsp").forward(request, response);
}`
and my jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center : myCenter,
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),
mapProp);
var marker = new google.maps.Marker({
position : myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width: 500px; height: 380px;"></div>
</body>
</html>
So instead of var myCenter = new google.maps.LatLng(51.508742, -0.120850);
I want pass my array. I think that could be done with JSON but I don't sure and don't know how.
Thanks for any help!
Few things to nottice:
You cannot read the Java List in javascript.
You must return the result in some way to be able to access in the javascript (client) side.
How to get the list in the client side?
You can choose one of this 2 options:
Use an Ajax call (for example):
$.get( "urlToMethod", {
"someVariable": someValue
}).done(function( data ) {
// in data you have the list of markers
}).error(function (data) {
// in data you have exception or the error
});
Java mapping:
#RequestMapping(value = "urlToMethod")
public String[] getMarkers (
HttpServletRequest httpRequest,
HttpServletResponse httpResponse,
#RequestParam(value = "someVariable") String someVariable) {
// get the markers and return a String[] or JSONArray!!!
}
Put the list into an JSP fied and read it in the script:
Java side (create a HelperClass if necessary)
model.addAttribute("markers", markersList);
Javascript
markers = $("#markers").val();
JSP
<form:hidden path="markers" id="markers" />
How to read the Java List in javascript:
Also here you can use any of this options:
You cannot read a List in javascript, but you can read a String or String[] (don't use double or float for the GPS lat/long due loosing of precision).
Create a JSONArray of the markers like in this answer:
NOTE: I assume you have JQuery in your project, also be careful because in Ajax solutions Spring is used, check here if you don't have it in your project.

Error showing GSheet range using Google Visualization API in Google Apps Script Web App

I'm trying to display a Google Spreadsheet range using Google Table Visualization API via Google Apps Script Web App. I plan to deploy the Web App into a Google Site. When I copy the code to a Google Apps Script Web App Project and deploy the web app, the query response is "Bad Request [400]". How do I debug further?
Alternative Solutions:
Manual effort: Google Sites has a gadget to pull a Gspreadsheet range onto a webpage, but I want to do it programmatically for 70 different ranges and pages.
Pure Google Apps Script: I can programmatically create copies of a web page template containing Table Gadgets and edit table range. There is a known issue that breaks gadgets when you edit the HTML content (google-apps-script-issues #572).
Source Google Spreadsheet (fake public data)
https://docs.google.com/spreadsheets/d/1miOxJ3jPCLE66mWcZmd2q-1YAu6so-GbxjcmIDtXUV4
JS Fiddle code works. I can query the Google Spreadsheet and draw the Google Visualization Table.
https://jsfiddle.net/xcghpgmt/6/
Also works as a snippet.
function drawChart() {
var key = '1miOxJ3jPCLE66mWcZmd2q-1YAu6so-GbxjcmIDtXUV4';
var GID = 0;
var range = 'A3:h18';
var queryString = 'https://docs.google.com/spreadsheets/d/'+key+'/gviz/tq?gid='+GID+'&range='+range;
// Set Data Source
var query = new google.visualization.Query(queryString);
// Send the query with callback function
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Handle Query errors
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
// Draw Chart
var data = response.getDataTable();
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data);
}
google.load('visualization', '1', {packages:['table'], callback: drawChart});
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile("Index").evaluate();
html.setTitle("Dynamic Webpage");
return html;
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
Index.html
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<div id="chart_div"></div>
</body>
<?!= include('JavaScript.html'); ?>
</html>
Javascript.html
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function drawChart() {
var key = '1miOxJ3jPCLE66mWcZmd2q-1YAu6so-GbxjcmIDtXUV4';
var GID = 0;
var range = 'A3:h18';
var queryString = 'https://docs.google.com/spreadsheets/d/'+key+'/gviz/tq?gid='+GID+'&range='+range;
// Set Data Source
var query = new google.visualization.Query(queryString);
// Send the query with callback function
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Handle Query errors
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
// Draw Chart
var data = response.getDataTable();
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data);
}
google.load('visualization', '1', {packages:['table'], callback: drawChart});
</script>
You haven't set the sandboxing for your application properly, so the caja sanitization is stripping out the jsapi.
Change:
function doGet() {
var html = HtmlService.createTemplateFromFile("Index").evaluate();
html.setTitle("Dynamic Webpage");
return html;
}
To:
function doGet() {
var html = HtmlService.createTemplateFromFile("Index").evaluate();
html.setTitle("Dynamic Webpage").setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
You can remove the sandboxing statement altogether from the include() function, since it's the application you need to sandbox. Better yet delete include() and use this in Index.html instead:
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>

Converting Serverside C# to ASP.NET Web API

After posting on how to get server side information to JS (on client side) link here, I was advised to create my server side logic into a Web Api in order to expose data via HTTP through a JQuery AJAX call. After looking through a lot of documentation, and even a tutorial series online hosted by Microsoft, I found little to no good instruction. Previously, I was calling my serverside methods through inline C# calls in my js script, but learned that because C# is precompiled, it simply just "fills in" the values returned by the C# functions.
Just for a reference as to how I am improperly calling my C# methods.
This is my front end: Login.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!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 runat="server">
<title>PAM testing</title>
<link rel="stylesheet" type="text/css" href="Styles/Site.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="Scripts/JScript.js"></script>
</head>
<body>
<div id="banner">PAM Testing Tool</div>
<div id="content">
<form id="form1" runat="server" style="margin-left: 25%; text-align: center; height: 41px; width: 292px;">
<%--Login ASP Object--%>
<asp:Login ID="Login1" runat="server" onclick="process()"></asp:Login>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" style="text-align: center" ValidationGroup="Login1" />
</form>
<%--TEST AREA--%>
<script type="text/javascript">
function logCookie(){
document.cookie = "user=" + document.getElementById("Login1_UserName").value;// this is the id of username input field once displayed in the browser
}
function testFunction() {
<%=Login1_Authenticate() %>;
}
function process(){
logCookie();
testFunction();
}
</script>
</div>
</body>
</html>
My C# code looks like this
Login.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.EnterpriseServices;
public partial class Login : System.Web.UI.Page
{
int status;
int role;
SqlConnection conn;
SqlCommand command;
SqlDataReader reader;
protected string Login1_Authenticate()
{
// create an open connection
conn =
new SqlConnection("Data Source=xxx;"
+ "Initial Catalog=xxx;"
+ "User ID=xxx;Password=xxx");
conn.Open();
//string userName;
//userName = Convert.ToString(Console.ReadLine());
// create a SqlCommand object for this connection
command = conn.CreateCommand();
command.CommandText = "EXEC dbo.SP_CA_CHECK_USER #USER_ID = '"+Login1.UserName+"', #PASSWORD = '"+Login1.Password+"'";
command.CommandType = CommandType.Text;
// execute the command that returns a SqlDataReader
reader = command.ExecuteReader();
// display the results
while (reader.Read())
{
status = reader.GetInt32(0);
}
// close first reader
reader.Close();
//----------
existTest();
return "the login process is finished";
}
public static string GetData(int userid)
{
/*You can do database operations here if required*/
return "my userid is" + userid.ToString();
}
public string existTest()
{
if (status == 0)
{
//login
Session["userID"] = Login1.UserName;
command.CommandText = "EXEC dbo.SP_CA_RETURN_USER_ROLE #USER_ID = '" + Login1.UserName + "'";
reader = command.ExecuteReader();
while (reader.Read())
{
role = reader.GetInt32(0);
}
Session["roleID"] = role;
if (Session["userID"] != null)
{
string userID = (string)(Session["userID"]);
//string roleID = (string)(Session["roleID"]);
}
Response.Redirect("Home.aspx");
}
else
{
//wrong username/password
}
// close the connection
reader.Close();
conn.Close();
return "process complete";
}
}
How can I convert my C# into Web api's? I would very much appreciate it if any answers could link me to good documentation or tutorials.
Moving this into Web API would require creating a new Web API project, setting up your appropriate controllers, and moving Form Control to parameters to pass into the Controller methods. Please visit this tutorial for more information on getting started with ASP.NET Web MVC: Getting Started With ASP-NET Web API
Please Note: Executing dynamic SQL the way you are doing in the above code leaves your application open to SQL Injection attacks! Please consider using parameterized SQL instead.

Categories

Resources