desktop notification using javascript in windows form - javascript

i am new to this and i am creating simple application in which i click a button and a notification on desktop should be displayed. i am doing this in windows form c#
the error is " NullReferenceException was unhandled
i have one button Notify in form1. i have tried this:
form1.cs
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.ScriptErrorsSuppressed = true;
}
private void btnNotify_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("notifyMe");
}
private void Form1_Load(object sender, EventArgs e)
{
string CurrentDirectory = Directory.GetCurrentDirectory();
webBrowser1.Navigate(Path.Combine(CurrentDirectory,"HTMLPage1.html"));
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.ObjectForScripting = this;
code for HTMLPage1.html :
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script language="javascript" type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: "Hey there! You've been notified!",
});
notification.onclick = function () {
window.open("http://stackoverflow.com/a/13328397/1269037");
};
}
}
</script>
</head>
<body>
</body>
</html>
even if i simply put alert("Hi") in notifyMe() function, nothing else. still it displays the same error.

I have tried your code.. you should use
document.attachEvent('DOMContentLoaded', function () {..
Instead of
document.addEventListener("..
That worked from here...read more about it here https://stackoverflow.com/a/1695383/4155741
you should also remove that comma at the end of .. body: "Hey there! You've been notified!", as it prevent the script from be compiled.

You have to put your html and scripts in the debug directory if they are not automatically placed. Thats where getcurrentdirectory() hits.

Related

JavaFX JSBridge doesn't work after page load

I have a strange problem; JSBridge doesn't work after the page loads but it does when the button is clicked.
Test site:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body bgcolor="#A0BEC4">
<input type="button" value="PLAY" onclick="play()"><br><br>
<script>
window.onload = function() { //does not work
stb.play("hello3");
}
function play() { // work
stb.play("hello2");
}
window.addEventListener('load', (event) => {
stb.play("hello4"); //does not work
});
stb.play("hello"); //does not work
function checkJSBridge(){ // !!! WORK !!!
if (typeof (stb.play) === "function") {
stb.play("WORK");
clearTimeout(bridge_timer);
}
}
let bridge_timer = setTimeout(checkJSBridge, 1000);
</script>
</body>
</html>
My code (JavaFX 18.0.1 and JDK 18.0.1.1):
private WebEngine webEngine = webView.getEngine();
private Worker<?> engineWorker = webEngine.getLoadWorker();
private JSBridge bridge = new JSBridge();
#Override
public final void start(Stage stage) throws Exception {
engineWorker.stateProperty().addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == State.SUCCEEDED) {
JSObject jsobj = (JSObject) webEngine.executeScript("window");
jsobj.setMember("stb", bridge);
}
}
});
}

How to connect SignalR Client on mobile device

Now i am developing selfhost signalr server application using VS2012 and client application using HTML/JS WebUI in Mosync IDE. When communication between client and server application, the signalr hub is successfully created on all browser and android emulator. But its doesn't work when i am using USB Debugging on my mobile. its produce 'undefined' message. How to make successful connection on my mobile. Please guide me.
Server side code:
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.Reflection;
using System.IO;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.Cors;
using Microsoft.Owin;
using Owin;
namespace SignalRServer
{
public partial class Form1 : Form
{
private IDisposable signalR { get; set; }
public string ServerURI;
MyNewHub h = new MyNewHub();
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
writeToConsole("Starting server...");
btnStart.Enabled = false;
Task.Run(() => StartServer());
}
private void StartServer()
{
try
{
//signalR = WebApp.Start(ServerURI);
if (File.Exists(Application.StartupPath + "\\IPAddress.txt"))
{
ServerURI = System.IO.File.ReadAllText(Application.StartupPath + "\\IPAddress.txt").Trim();
signalR = WebApp.Start(ServerURI);
}
else
{
MessageBox.Show("IPAddress not found");
}
}
catch (TargetInvocationException)
{
writeToConsole("Server failed to start. A server is already running on" + ServerURI);
this.Invoke((Action)(() => btnStart.Enabled = true));
return;
}
this.Invoke((Action)(() => btnStart.Enabled = true));
writeToConsole("Server started at" + ServerURI);
}
public void writeToConsole(string message)
{
if (RichTextBoxConsole.InvokeRequired)
{
this.Invoke((Action)(() => writeToConsole(message)));
return;
}
RichTextBoxConsole.AppendText(message + Environment.NewLine);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (signalR != null)
{
signalR.Dispose();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string msg = txtMesage.Text;
h.Receive(msg);
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
[HubName("myNewHub")]
public class MyNewHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
Program.mainform.writeToConsole(name + " : " + message);
}
public void Receive(string msg)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyNewHub>();
context.Clients.All.addMessage("Admin", msg);
}
public override Task OnConnected()
{
Program.mainform.writeToConsole("Client Connected:" + Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Program.mainform.writeToConsole("Client DisConnected: " + Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
}
Client side code:
<!DOCTYPE html>
<!--
* #file index.html
*
* Template application that shows examples of how to access
* device services from JavaScript using the Wormhole library.
-->
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
<meta name="viewport" content="width=320, user-scalable=no">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Wormhole Template App</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="js/wormhole.js"></script>
<script src="js/jquery-1.6.4.min.js"></script>
<script src="js/jquery.signalR-2.0.3.min.js"></script>
<script src="http://192.168.0.7:8080/signalr/hubs"></script>
<script type="text/javascript">
function clientconnect()
{
alert("Start Button Clicked");
$.connection.hub.url = "http://192.168.0.7:8080/signalr";
// Declare a proxy to reference the hub.
var chats = $.connection.myNewHub;
alert(chats);
// Create a function that the hub can call to broadcast messages.
chats.client.addMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chats.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
}
</script>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<input type="button" value="Start" onclick="clientconnect()"/>
<ul id="discussion"></ul>
</div>
</body>

Understanding XSockets.NET pubsub: producing and consuming messages from JavaScript

Let's say I've the following sample code (JavaScript):
// Client A
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.publish("some:channel", { text: "hello world" });
});
// Client B (subscriber)
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.on("some:channel", function(message) {
// Subscription receives no message!
});
});
Client B never receives a message. Note that this is a sample code. You might think that I don't receive the message because Client B got connected after Client A sent the message, but in the actual code I'm publishing messages after both sockets are opened.
The server-side XSocketsController is working because I'm using it for server-sent notifications.
What am I doing wrong? Thank you in advance!
It looks like you have mixed up the pub/sub with the rpc, but I cant tell for sure if you do not post the server side code as well.
But what version are you using? 3.0.6 or 4.0?
Once I know the version and have the server side code I will edit this answer and add a working sample.
EDIT (added sample for 3.0.6):
Just wrote a very simple chat with pub/sub.
Controller
using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace Demo
{
public class SampleController : XSocketController
{
/// <summary>
/// By overriding the onmessage method we get pub/sub
/// </summary>
/// <param name="textArgs"></param>
public override void OnMessage(ITextArgs textArgs)
{
//Will publish to all client that subscribes to the value of textArgs.#event
this.SendToAll(textArgs);
}
}
}
HTML/JavaScript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/XSockets.latest.min.js"></script>
<script>
var conn;
$(function() {
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Sample');
conn.onopen = function(ci) {
console.log('open', ci);
conn.on('say', function(d) {
$('div').prepend($('<p>').text(d.text));
});
}
$('input').on('keydown', function(e) {
if (e.keyCode == 13) {
conn.publish('say', { text: $(this).val() });
$(this).val('');
}
});
});
</script>
</head>
<body>
<input type="text" placeholder="type and hit enter to send..."/>
<div></div>
</body>
</html>
Regards
Uffe

Open a popup containing ASPX postback result

I have an ASPX page with many fields that generate PDF documents when I click an "export to PDF" button.
I'd now like to have a "print PDF" button in JavaScript that does something like this:
w = window.open(?);
w.print();
w.close();
where "?" will perform the same postback as my "export to PDF" button.
If you need to submit (postback) your form to new window you can try to change form target to fake, like:
var form = $("form");
form.attr("target", "__foo");
Submit a form.
form.submit();
And remove the target (setitmeout(,1) - pot the event in end of js "event-queue", in our case - after form submitting):
setTimeout(function () { form.removeAttr("target"); }, 1);
Also, before submit you can try to open window with __foo id for more styling, and the form will submitted (postback) in this window instead of a new one:
var wnd = window.open('', '__foo', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes');
But I have no idea how to handle the submitted window and catch the onload or jquery's ready event. If you can do it share the workaround please and call the wnd.print(); You can play with iframes inside this wnd and maybe you will find a solution.
Updated:
Try to have a look in this prototype [tested in Chrome]:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
function PrintResult() {
var wnd, checker, debug;
debug = true;
// create popup window
wnd = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');
// create "watermark" __loading.
wnd.document.write("<h1 id='__loading'>Loading...</h1>");
// submit form to popup window
$("form").attr("target", "__foo");
setTimeout(function() { $("form").removeAttr("target"); }, 1);
if (debug)
{
$("#log").remove();
$("body").append($("<div id='log'/>"));
}
// check for watermark
checker =
setInterval(function () {
if (debug) $("#log").append('. ');
try {
if (wnd.closed) { clearInterval(checker); return; }
// if watermark is gone
if (wnd.document == undefined || wnd.document.getElementById("__loading") == undefined) {
if (debug) $("#log").append(' printing.');
//stop checker
clearInterval(checker);
// print the document
setTimeout(function() {
wnd.print();
wnd.close();
}, 100);
}
} catch (e) {
// ooops...
clearInterval(checker);
if (debug) $("#log").append(e);
}
}, 10);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="ReportButton" OnClick="ReportRenderClick" Text="Export to PDF" OnClientClick="PrintResult()"/>
<asp:Button runat="server" Text="Just a button."/>
</div>
</form>
</body>
</html>
And here is .cs file:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ReportRenderClick(object sender, EventArgs e)
{
Response.Clear();
Thread.Sleep(2000);
Response.ContentType = "application/pdf";
Response.WriteFile("d:\\1.pdf");
//Response.ContentType = "image/jpeg";
//Response.WriteFile("d:\\1.jpg");
//Response.Write("Hello!");
Response.End();
}
}
Open the pdf window with IFrame and you could do this:
Parent Frame content
<script>
window.onload=function() {
window.frames["pdf"].focus();
window.frames["pdf"].print();
}
</script>
<iframe name="pdf" src="url/to/pdf/generation"></iframe>
Inspired from this https://stackoverflow.com/a/9616706
In your question tag you have the asp.net tag, so I guess you have access to some kind of ASP.NET server technology.
I would suggest to do it like this:
Create a HttpHandler or an ASP.NET MVC action that returns a FileContentResult
In your page, use this code to download and print the file (actually found it here, pasting it for future reference!)
Click here to download the printable version
There are some good tutorials on writing the server side:
Walkthrough: Creating a Synchronous HTTP Handler
How to get particular image from the database?
And one of my own: Download PDF file from Web location and Prompt user SaveAs box on client in web-Application ASP C#

Javascript on code behind

I've been trying to run the code if any of the conditions get true. Its a dialog box which popups after postback created on Jquery Impromptu. I've tried to run the same code on a different project and its working fine however It doesn't show anything the condition met true
ASPX CODE
<!-- JavaScript -->
<script type="text/javascript" src="Scripts/jquery.js"></script>
<script type="text/javascript" src="Scripts/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="Scripts/wufoo.js"></script>
<script type="text/javascript" src="Scripts/jquery-impromptu.2.6.min.js"></script>
<script type="text/javascript">
function confirmSubmit() {
$.prompt('Are you sure you want to submit?'
, {
buttons: { Ok: true, Cancel: false }
, callback: confirmSubmitResult
}
);
return false;
}
function confirmSubmitResult(v, m, f) {
if (v) //post back if the user clicked OK
$('#<%# btnSubmit.ClientID %>').click();
}
</script>
.CS CODE
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
TextBox2.Attributes.Add("readonly", "readonly");
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string prompt = "<script>$(document).ready(function(){{$.prompt('{0}!');}});</script>";
string message = string.Format(prompt, "This message is coming after postback");
if (TextBox2.Text.Length == 0 || TextBox1.Text.Length == 0)
{
ClientScript.RegisterStartupScript(typeof(Page), "message", message);
}
A little help will be highly appreciated

Categories

Resources