Call javascript function from windows service c# - javascript

I need to call a javascript function inside a chrome-window from a windows service written in c#.
The browser is entirely at my disposal so I can configuration is no problem.
For example, the windows service is a file checker, when a certain file is changed there has to popup a js alert.
-EDIT-
The following works fine for client to client communication (server-side code).
So when a specific event happens on the server I can display this on the client (I hoped commented would do that)
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using SignalR.Hosting.Self;
using SignalR.Hubs;
namespace Net.SignalR.SelfHost
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8081/";
var server = new Server(url);
server.MapHubs();
server.Start();
Console.WriteLine("SignalR server started at " + url);
Console.ReadLine();
// Clients[collection].flush("bericht: " + message + collection);
}
//public void PushMessage(string bericht)
//{
// var hubConnection = new HubConnection("http://localhost:8081/");
// var serverHub = hubConnection.CreateProxy("CollectionHub");
// serverHub.On("flush", message => System.Console.WriteLine(message));
// hubConnection.Start().Wait();
// serverHub.Invoke("Subscribe", "Product");
// string line = null;
// while ((line = bericht) != null)
// {
// serverHub.Invoke("Publish", line, "Product").Wait();
// }
// System.Console.Read();
//}
public class CollectionHub : Hub
{
public void Subscribe(string collectionName)
{
Groups.Add(Context.ConnectionId, collectionName);
Console.WriteLine("Subscribed to: " + collectionName);
//serverHub.Invoke("Publish", "dit is een eerste test", "Product").Wait();
}
public Task Unsubscribe(string collectionName)
{
return Clients[collectionName].leave(Context.ConnectionId);
}
public void Publish(string message, string collection)
{
Clients[collection].flush("bericht: " + message + collection);
}
}
}
}

Sounds like you are describing SignalR.
What is ASP.NET SignalR?
ASP.NET SignalR is a new library for ASP.NET
developers that makes it incredibly simple to add real-time web
functionality to your applications. What is "real-time web"
functionality? It's the ability to have your server-side code push
content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables
bi-directional communication between the browser and server. SignalR
will use WebSockets under the covers when it's available, and
gracefully fallback to other techniques and technologies when it
isn't, while your application code stays the same.
SignalR also provides a very simple, high-level API for doing server
to client RPC (call JavaScript functions in your clients' browsers
from server-side .NET code) in your ASP.NET application, as well as
adding useful hooks for connection management, e.g. connect/disconnect
events, grouping connections, authorization.
What can you do with ASP.NET SignalR?
SignalR can be used to add any
sort of "real-time" web functionality to your ASP.NET application.
While chat is often used as an example, you can do a whole lot more.
Any time a user refreshes a web page to see new data, or the page
implements Ajax long polling to retrieve new data, is candidate for
using SignalR.
What it basicly does, is giving you access to the client AND server side functions in both directions, a simple example of it's usage can be found on the asp.net website which will give you a good idea on how to use it and what it's capable of doing.

You want to be using something like signal IR to do that, its what its designed for, essentially you are describing real time functionality;
Signal IR can be found here and has a great section on javascript in its wiki
In particular you probably want to take a look at Hubs

Related

Making a simple ASP webpage that displays updating values from C# program

I have never used ASP.NET before and I don't quite understand how the MVC system works, but my application is much more simple than the tutorials provided.
I have a webpage in HTML, and I currently have a C# program that gets key presses from my keyboard (Making a webpage that displays key presses). Both of these work, and the C# program prints to the terminal.
I can't however, seem to connect the two, by making a web page that has data bindings so that whenever a C# class updates, it changes the HTML content without page refresh.
This would probably require learning a lot, but I'm hoping to make it with a few files (maybe a controller isn't needed since the page has no interaction?). I'm not sure how to even make a DOTNET project, as the sample one has many built-in pages and routes that I don't understand.
So basically, this is my C# program (with DLL in the same dir)
using System;
using WootingAnalogSDKNET;
// We'll also include this for the Thread.Sleep call we'll have later on
using System.Threading;
using System;
using System.IO;
using System.Net;
using System.Threading;
Console.WriteLine("Hello Analog SDK!");
// Initialise the SDK
var (noDevices, error) = WootingAnalogSDK.Initialise();
// If the number of devices is at least 0 it indicates the initialisation was successful
if (noDevices >= 0) {
Console.WriteLine($"Analog SDK Successfully initialised with {noDevices} devices!");
}
else {
Console.WriteLine($"Analog SDK failed to initialise: {error}");
System.Environment.Exit(1);
}
while (true) {
var (keys, readErr) = WootingAnalogSDK.ReadFullBuffer(20);
if (readErr == WootingAnalogResult.Ok)
{
// Go through all the keys that were read and output them
foreach (var analog in keys)
{
Console.Write($"({analog.Item1},{analog.Item2})");
}
// We want to put on the new line character only if keys have been read and output to the console
if (keys.Count > 0)
Console.WriteLine();
}
else
{
Console.WriteLine($"Read failed with {readErr}");
// We want to put more of a delay in when we get an error as we don't want to spam the log with the errors
Thread.Sleep(1000);
}
// We want to have a bit of a delay so we don't spam the console with new values
Thread.Sleep(100);
}
Thank you in advance for you help!

Android Calling JavaScript functions in Button

I've an Android Activity and I've got a Button that button need to access some Javascript function. Simply my app get the user info(ID,pass) then go to web page(this operation doing backgrun with asynctask class) write these two info as ID and pass then user click the Log In button in my app button has to use some js function
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
this is the func. i need to use
My post and get request for connection the site are
POST//
URL url = new URL(params[0]); //http://login.cu.edu.tr/Login.aspx? site=https://derskayit.cu.edu.tr&ReturnUrl=%2f
connection=(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
these codes for the put the ID and pass
GET //
reader= new BufferedReader((new InputStreamReader(connection.getInputStream())));
StringBuilder builder = new StringBuilder();
String line;
while((line= reader.readLine())!=null){
builder.append(line + "\n");
}
text=builder.toString();
there is any help or suggestion for me i am very confused about that situation and i feel really bad myself thanks for helps anyway. Have a nice day
For using Javascript without a webView to make requests!
The question has already an answer here in this question
The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.
Also a similar question was asked here
You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());
JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");
However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.
Is there a reason you don't use a hidden WebView and simply inject your code?
// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);
Otherwise:
Yes you can make HTTP POST and HTTP GET requests without using WebView. But if you want to use a webView remember Javascript in a webview is disabled by default (for security purposes). So before calling any javascript functions make sure you enable javascript in your webview like this
webView.getSettings().setJavaScriptEnabled( true );
And after that javascript will be enabled in your webView.
But in case you do not want to use a webview and javascript to make http requests. There is a lot of alternative methods you can define a Button in your activity's layout in xml. And respond with a http request on button Clicked listener!
Also remember making http Request using Android/Java default classes is a huge task and error prone and requires you to care about using async tasks to avoid blocking the UI thread.
Alternatively
In android we use ready-made library to make http requests. Google has a good library called Volley. it is easy to customize,respond to errors and it automatically making request out of the main thread.See more explanation here!. If there is still some problems comment below!

How to stream audio from browser to WebRTC native C++ application

I have so far managed to run the following sample:
WebRTC native c++ to browser video streaming example
The sample shows how to stream video from a native C++ application (peerconnection_client.exe) to the browser (I am using Chrome). This works fine and I can see myself in the browser.
What I would like to do is to stream audio from the browser to the native application but I am not sure how. Can anyone give me some pointers please?
I'm trying to find a way to stream both video and audio from browser to my native program. and here is my way so far.
To stream video from browser to your native program without gui, just follow the example here. https://chromium.googlesource.com/external/webrtc/+/refs/heads/master/examples/peerconnection/client/
use AddOrUpdateSink to add your own VideoSinkInterface and you will receive your frame data in callback void OnFrame(const cricket::VideoFrame& frame). Instead of render the frame to GUI as the example does, you can do whatever you want.
To stream audio from browser to your native program without real audio device. you can use a fake audio device.
modify variable rtc_use_dummy_audio_file_devices to true in file https://chromium.googlesource.com/external/webrtc/+/master/webrtc/build/webrtc.gni
invoke the global static function to specify the filename webrtc::FileAudioDeviceFactory::SetFilenamesToUse("", "file_to_save_audio");
patch file_audio_device.cc with the code blew. (as I write this answer, FileAudioDevice has some issues, may already be fixed)
recompile your program, touch file_to_save_audio and you will see pcm data in file_to_save_audio after webrtc connection is established.
patch:
diff --git a/webrtc/modules/audio_device/dummy/file_audio_device.cc b/webrtc/modules/audio_device/dummy/file_audio_device.cc
index 8b3fa5e..2717cda 100644
--- a/webrtc/modules/audio_device/dummy/file_audio_device.cc
+++ b/webrtc/modules/audio_device/dummy/file_audio_device.cc
## -35,6 +35,7 ## FileAudioDevice::FileAudioDevice(const int32_t id,
_recordingBufferSizeIn10MS(0),
_recordingFramesIn10MS(0),
_playoutFramesIn10MS(0),
+ _initialized(false),
_playing(false),
_recording(false),
_lastCallPlayoutMillis(0),
## -135,12 +136,13 ## int32_t FileAudioDevice::InitPlayout() {
// Update webrtc audio buffer with the selected parameters
_ptrAudioBuffer->SetPlayoutSampleRate(kPlayoutFixedSampleRate);
_ptrAudioBuffer->SetPlayoutChannels(kPlayoutNumChannels);
+ _initialized = true;
}
return 0;
}
bool FileAudioDevice::PlayoutIsInitialized() const {
- return true;
+ return _initialized;
}
int32_t FileAudioDevice::RecordingIsAvailable(bool& available) {
## -236,7 +238,7 ## int32_t FileAudioDevice::StopPlayout() {
}
bool FileAudioDevice::Playing() const {
- return true;
+ return _playing;
}
int32_t FileAudioDevice::StartRecording() {
diff --git a/webrtc/modules/audio_device/dummy/file_audio_device.h b/webrtc/modules/audio_device/dummy/file_audio_device.h
index a69b47e..3f3c841 100644
--- a/webrtc/modules/audio_device/dummy/file_audio_device.h
+++ b/webrtc/modules/audio_device/dummy/file_audio_device.h
## -185,6 +185,7 ## class FileAudioDevice : public AudioDeviceGeneric {
std::unique_ptr<rtc::PlatformThread> _ptrThreadRec;
std::unique_ptr<rtc::PlatformThread> _ptrThreadPlay;
+ bool _initialized;;
bool _playing;
bool _recording;
uint64_t _lastCallPlayoutMillis;
I know this is an old question, but I struggled myself to find a solution currently so I thought sharing is appreciated.
There's is one more or less simple way to get an example running which streams from the browser to native code.You need the webrtc source http://www.webrtc.org/native-code/development
The two tools you need are the peerconnection server and client. Both can be found in the folder talk/example/peerconnection
To get it working you need to patch it to enable DTLS for the peerconnection client. So patch it with the patch provided here https://code.google.com/p/webrtc/issues/detail?id=3872 and rebuild the client. Now you are set up on the native site!
For the browser I recommend the peer2peer example from here https://github.com/GoogleChrome/webrtc after starting the peerconnection_server and connection the peerconnection_client try to connect with the peer2peer example.
Maybe a connection constraint is necessary:
{
"DtlsSrtpKeyAgreement": true
}
you could use the following example which implement a desktop client for appRTC.
https://github.com/TemasysCommunications/appRTCDesk
this completes and interop with the web client, android client and iOs client provided by the open source implementation at webrtc.org, giving you a full suite of clients to work with their free server. peer connection_{client|server} is an old example from the lib jingle time (pre webrtc) and does not interop with anything else.

Issuing MySQL queries from standalone Javascript (no, I'm not crazy, my vendor is)

Our lab recently got an Agilent Bravo pipetting robot (it precisely dispenses tiny quantities of liquid for doing rapidly doing many biology or chemistry experiments). Apparently the glue language for extending the software that controls the robot is Javascript! I know, right?
Anyway, for the robot to be useful, we have to be able to retrieve information about the samples it's handling but every example I can find for sending queries in Javascript depends on PHP and usually the assumption that the script is running in a web-browser.
Is there some way to wrap a command-line mysql or is there already some library or utility that does this? The OS we're running is Windows 7.
Wow, thanks for the quick and useful answers.
In addition, I found a platform-specific answer: http://www.velocity11.com/techdocs/helpsystem/vworks_ug/usingjavascriptinvworks.html
Long story short, VWorks (control software for Agilent's equipment) has a run() global function that does exactly that. But, the above answers are probably more useful to this site than my own is, because they are relevant to a broader range of problems, so thanks again.
"sending queries in Javascript depends on PHP"
no it doesn't.
Just send retreive data(json) using ajax, I'd use http://api.jquery.com/jQuery.ajax/.
Yes, you can use ADO with Javascript on Windows to access various data sources. Search for "jscript ado" and you will get lots of information on this, e.g.:
// path to database
var DBpath="\\\\Server\\Path\\myDB.mdb"
// set up a few object constants
var adLockReadOnly=1
var adOpenForwardOnly=0
var adCmdText=1
// create and open a new connection (MSAccess)
var cnn=new ActiveXObject("ADODB.connection")
cnn.Provider = "Microsoft.Jet.OLEDB.4.0;Data Source=" + DBpath
try
{
cnn.open
}
catch(err)
{
// could not open connection
// view details in err.Description and err.Number
return 0
}
//open a read only recordset
var rs = new ActiveXObject("ADODB.Recordset")
try
{
rs.Open("Select * from myTable", cnn, adOpenForwardOnly, adLockReadOnly)
}
catch(err)
{
// could not open recordset
return 0
}
while(!rs.EOF)
{
// do something
rs.movenext
}
rs.close
Update:
According to info here, you can develop plugins using Visual Studio/C#. Maybe that is of some use? You could write a plugin to send the data somewhere...

In a .NET application, is it possible to get a representation of the DOM as a web browser would see it?

I need for a server side process to be able to produce the same view of the HTML dom for a web page as a web browser (I am aware that the dom representation is browser specific, so don't mind a non cross browser solution).
I need to be able to work my way back to a user selection on a web page at a later date. Since there is no firm relationship between the raw HTML for a page, and the Dom that a browser constructs, this is proving very difficult to say the least!
My thinking is now that if I can produce the same view of the document in a server side process, then I may be able to achieve this.
Does anyone have experience of this?
Thanks
OK, different angle.
What about using the WebBrowser Control?
As far as I know, there's nothing preventing web application from adding reference to System.Windows assembly and using it.
Bit of a long shot, but IMO worth trying!
OK... for what it's worth, I was able to successfully use WebBrowser control (yeah, from System.Windows.Forms) to load remote page and iterate its DOM freely.
The bricks in the wall I faced and destroyed are below.
Full code, which for the sake of example show all images in the remote page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
using System.Text;
namespace TestZone
{
public partial class _Default : System.Web.UI.Page
{
private bool waiting = false;
private WebBrowser browser = null;
protected void Page_Load(object sender, EventArgs e)
{
Thread thread = new Thread(new ParameterizedThreadStart(LoadRemotePage));
thread.SetApartmentState(ApartmentState.STA);
waiting = true;
thread.Start(this);
while (waiting)
{
Thread.Sleep(10);
}
}
private void LoadRemotePage(object sender)
{
try
{
browser = new WebBrowser();
browser.Tag = sender;
browser.Navigate("http://stackoverflow.com/questions/4082249/in-a-net-application-is-it-possible-to-get-a-representation-of-the-dom-as-a-web/4085520");
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
while (browser.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
browser.Dispose();
}
catch (Exception ex)
{
litDebug.Text = "Error while initializing browser control: " + ex.ToString().Replace("\n", "<br />");
(sender as _Default).waiting = false;
}
finally
{
}
//hgcDebug.GetType().InvokeMember("InnerHtml", BindingFlags.SetProperty, null, hgcDebug, new object[] { "done" });
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
HtmlElementCollection collection = browser.Document.GetElementsByTagName("img");
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Total of {0} images:<br />", collection.Count);
for (int i = 0; i < collection.Count; i++)
sb.AppendFormat("name: {0}, src: {1}<br />", collection[i].GetAttribute("name"), collection[i].GetAttribute("src"));
litDebug.Text = sb.ToString();
}
catch (Exception ex)
{
litDebug.Text = "Error while analyzing remote page: " + ex.ToString().Replace("\n", "<br />");
}
finally
{
((sender as WebBrowser).Tag as _Default).waiting = false;
}
}
}
}
Bumps along the way, if anyone is curious:
Exception while creating the WebBrowser control.. thread was in wrong state. Fixed by moving the code to new thread explicitly setting the ApartmentState to STA.
Document property of the WebBrowser was null. First step of the fix was using the DocumentCompleted event instead of tring to access the Document right after Navigating.
Still no luck though, DocumentCompleted never occurred. To fix that I added the loop waiting until the ReadyState is complete. Done and working, but..
All this done, changing the literal from within the new thread had no effect on the actual GUI.. had to wait in the main thread until everything was done.
Hope this will come handy someday for someone, if not for the OP here. :)
Best you can achieve is using WebRequest to read the raw response (HTML output) of the page and assuming it's valid XHTML throw it into XmlReader and you have kind of DOM at hand, at least the nodes.
I've previously used an HTML parsing library called SgmlReader, which worked well for getting HTML tag soup into a workable DOM. I would be surprised if it always produces a DOM identical to what a browser would produce though.

Categories

Resources