Getting XMLHttpRequest to work on Windows Phone HTML5 App - javascript

In Microsoft Visual Studio Express I have started a new project using the "Windows Phone HTML5 App" template. If I run the emulator, everything works fine. Next I added the following JavaScript to the index.html page:
<script type="text/javascript">
window.onload = function(){
alert(window.location.href); // --> x-wmapp0:/Html/index.html
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
alert('ON READY STATE CHANGE');
if(xmlhttp.readyState==4){
alert(xmlhttp.responseText);
}
}
//xmlhttp.open("GET","text.txt",true); // I have tried all of these
//xmlhttp.open("GET","Html/text.txt",true);
//xmlhttp.open("GET","/Html/text.txt",true);
xmlhttp.open("GET","x-wmapp0:/Html/text.txt",true);
xmlhttp.send();
}
</script>
Now when I run the app in the emulator I get the first alert with the window location, but do not get any alerts from the readyState or onreadystatechange. The text.txt file is on the same level as the index.html. I have run this code in IE10 and it works just fine. Any ideas on what I am doing wrong?
Update: I have deployed this on an actual Windows 8 phone and got the same result
Cheers

Here is what Microsoft told me from MSDN
XMLHttpRequest only works for retrieving network resources. i.e. You cannot use it to access content from your applications local storage, i.e. XAP or IsolatedStorage.
Here is an example of script + code which I have used in the past to work around this limitation:
HTML Page with JavaScript:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script type="text/javascript">
function LoadFile(SourceURL) {
try {
var httpfreq = new XMLHttpRequest();
httpfreq.onreadystatechange = function () {
filecontent.innerText = "httpfreq.onreadystatechange fired, readyState = " + httpfreq.readyState.toString();
if (httpfreq.readyState = 4) {
filecontent.innerText = "Status = " + httpfreq.status.toString();
if (httpfreq.status = 200) {
window.external.notify("Received content" + httpfreq.responseText);
filecontent.innerHTML = httpfreq.responseText;
}
else {
window.external.notify("Error loading page: " + SourceURL);
filecontent.innerText = "Error loading page " + SourceURL;
}
}
};
httpfreq.open("GET", SourceURL);
httpfreq.send(null);
}
catch (e) {
if (e.number = 0x80070005) {
LoadLocalFile(SourceURL, "GetResourceCallback");
}
else {
alert(e.name + " " + e.number.toString());
}
}
}
function LoadLocalFile(SourceURL, callbackfn) {
window.external.notify("GetResource?file=" + SourceURL + ";callback=" + callbackfn);
}
function GetResourceCallback(StringContent) {
filecontent.innerText = StringContent;
}
</script>
</head>
<body>
<p>
test page: notes.html
</p>
<p><input type="button" onclick="LoadFile('text.txt')" value="Load Local" /> </p>
<p><input type="button" onclick="LoadFile('http://www.somedomain.com/text.txt')" value="Load remote" /> </p>
<p>---------------------------</p>
<div id="filecontent"></div>
<p>---------------------------</p>
</body>
</html>
And the required App Host code (c#)
private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Script Notify : {0}",e.Value);
if (e.Value.Contains("GetResource?file="))
{
Dispatcher.BeginInvoke(() =>
{
String szArgs = e.Value;
string szResource = null;
string szCallbackFn = null;
char[] separators = new char[2] {'?',';'};
string[] parms = szArgs.Split(separators);
for (int i = 1; i < parms.Length; i++ )
{
if (parms[i].Contains("file="))
{
szResource = parms[i].Substring(5);
}
else if (parms[i].Contains("callback="))
{
szCallbackFn = parms[i].Substring(9);
}
}
if (!String.IsNullOrWhiteSpace(szResource) && !String.IsNullOrWhiteSpace(szCallbackFn))
{
// read local resource.
string szFileContent= "Resource not found!";
try
{
if (String.IsNullOrEmpty(webBrowser1.Base))
{
// if Base is not set then assume XAP file content.
szFileContent = ReadXAPResource(szResource);
}
else
{
// else assume IsolatedStorage
szFileContent = ReadISOFile(webBrowser1.Base, szResource);
}
}
catch (Exception)
{}
webBrowser1.InvokeScript(szCallbackFn, szFileContent);
}
});
}
}
private string ReadXAPResource(string szFile)
{
string szContent = "File Not Found";
try
{
// in my project HTML files are in the HelpContent folder...
StringBuilder szPath = new StringBuilder("HelpContent");
if (!szFile.StartsWith("/"))
szPath.Append("/");
szPath.Append(szFile);
StreamResourceInfo sri = Application.GetResourceStream(new Uri(szPath.ToString(), UriKind.Relative));
if (null != sri)
{
StreamReader strm = new StreamReader(sri.Stream);
szContent = strm.ReadToEnd();
}
}
catch (Exception) { }
return szContent;
}
private string ReadISOFile(string szBase, string szFile)
{
string szContent = "File Not Found";
try
{
string fullPath = szBase + szFile;
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfsInput = isf.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (null != isfsInput)
{
StreamReader strm = new StreamReader(isfsInput);
szContent = strm.ReadToEnd();
}
}
catch (Exception) { }
return szContent;
}

Related

How to send an image using websockets in java?

I am trying to send an image by drag and drop in send message area but its failing to do so. I dont know how to send an image in this code. Can someone please help me out?
ChatEndpoint.java
This is serverendpoint of websocket.I have four methods.onOpen,onClose,onMessage and onError.I am not doing anything in onOpen method.This method gets called when websocket establishes the connection.When the websocket tries to send message to the client,onMessage method gets called.Here the message sent from the jsp page(client) sends it in json string format to the server.The object mapper converts it to java object.I have also made an enum for MessageType having two options LOGIN and MESSAGE.I am checking inf the java object matches with the login message type then it stores the name of chat user from properties of user obtained from session object.It also then sends the session object to join method where the session is added to the list of session object.It also send the message the user has joined the chat room.If messagetype is a message then it sends it to send message method of room class where the message is sent back to the client using sendText.
#ServerEndpoint(value = "/chat")
public class ChatEndpoint {
private Logger log = Logger.getLogger(ChatEndpoint.class.getSimpleName());
private Room room = Room.getRoom();
#OnOpen
public void onOpen(final Session session, EndpointConfig config) {}
#OnMessage
public void onMessage(final Session session, final String messageJson) {
ObjectMapper mapper = new ObjectMapper();
ChatMessage chatMessage = null;
try {
chatMessage = mapper.readValue(messageJson, ChatMessage.class);
} catch (IOException e) {
String message = "Badly formatted message";
try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, message));
} catch (IOException ex) { log.severe(ex.getMessage()); }
} ;
Map<String, Object> properties = session.getUserProperties();
if (chatMessage.getMessageType() == MessageType.LOGIN) {
String name = chatMessage.getMessage();
properties.put("name", name);
room.join(session);
room.sendMessage(name + " - Joined the chat room");
}
else {
String name = (String)properties.get("name");
room.sendMessage(name + " - " + chatMessage.getMessage());
}
}
#OnClose
public void OnClose(Session session, CloseReason reason) {
room.leave(session);
room.sendMessage((String)session.getUserProperties().get("name") + " - Left the room");
}
#OnError
public void onError(Session session, Throwable ex) { log.info("Error: " + ex.getMessage()); }
}
Room.java
public class Room {
private static Room instance = null;
private List<Session> sessions = new ArrayList<Session>();
public synchronized void join(Session session) { sessions.add(session); }
public synchronized void leave(Session session) { sessions.remove(session); }
public synchronized void sendMessage(String message) {
for (Session session: sessions) {
if (session.isOpen()) {
try { session.getBasicRemote().sendText(message); }
catch (IOException e) { e.printStackTrace(); }
}
}
}
public synchronized static Room getRoom() {
if (instance == null) { instance = new Room(); }
return instance;
}
}
index.jsp
Here i am sending the wsUri which is stored in context param as ws://localhost:8080/single-room-chat/chat
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<% String WsUrl = getServletContext().getInitParameter("WsUrl"); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name='viewport' content='minimum-scale=1.0, initial-scale=1.0,
width=device-width, maximum-scale=1.0, user-scalable=no'/>
<title>single-room-chat</title>
<link rel="stylesheet" type="text/css" href="content/styles/site.css">
<script type="text/javascript" src="scripts/chatroom.js"></script>
<script type="text/javascript">
var wsUri = '<%=WsUrl%>';
var proxy = CreateProxy(wsUri);
document.addEventListener("DOMContentLoaded", function(event) {
console.log(document.getElementById('loginPanel'));
proxy.initiate({
loginPanel: document.getElementById('loginPanel'),
msgPanel: document.getElementById('msgPanel'),
txtMsg: document.getElementById('txtMsg'),
txtLogin: document.getElementById('txtLogin'),
msgContainer: document.getElementById('msgContainer')
});
});
</script>
</head>
<body>
<div id="container">
<div id="loginPanel">
<div id="infoLabel">Type a name to join the room</div>
<div style="padding: 10px;">
<input id="txtLogin" type="text" class="loginInput"
onkeyup="proxy.login_keyup(event)" />
<button type="button" class="loginInput" onclick="proxy.login()">Login</button>
</div>
</div>
<div id="msgPanel" style="display: none">
<div id="msgContainer" style="overflow: auto;"></div>
<div id="msgController">
<textarea id="txtMsg"
title="Enter to send message"
onkeyup="proxy.sendMessage_keyup(event)"
style="height: 20px; width: 100%"></textarea>
<button style="height: 30px; width: 100px" type="button"
onclick="proxy.logout()">Logout</button>
</div>
</div>
</div>
</body>
</html>
chatroom.js
var CreateProxy = function(wsUri) {
var websocket = null;
var audio = null;
var elements = null;
var playSound = function() {
if (audio == null) {
audio = new Audio('content/sounds/beep.wav');
}
audio.play();
};
var showMsgPanel = function() {
elements.loginPanel.style.display = "none";
elements.msgPanel.style.display = "block";
elements.txtMsg.focus();
};
var hideMsgPanel = function() {
elements.loginPanel.style.display = "block";
elements.msgPanel.style.display = "none";
elements.txtLogin.focus();
};
var displayMessage = function(msg) {
if (elements.msgContainer.childNodes.length == 100) {
elements.msgContainer.removeChild(elements.msgContainer.childNodes[0]);
}
var div = document.createElement('div');
div.className = 'msgrow';
var textnode = document.createTextNode(msg);
div.appendChild(textnode);
elements.msgContainer.appendChild(div);
elements.msgContainer.scrollTop = elements.msgContainer.scrollHeight;
};
var clearMessage = function() {
elements.msgContainer.innerHTML = '';
};
return {
login: function() {
elements.txtLogin.focus();
var name = elements.txtLogin.value.trim();
if (name == '') { return; }
elements.txtLogin.value = '';
// Initiate the socket and set up the events
if (websocket == null) {
websocket = new WebSocket(wsUri);
websocket.onopen = function() {
var message = { messageType: 'LOGIN', message: name };
websocket.send(JSON.stringify(message));
};
websocket.onmessage = function(e) {
displayMessage(e.data);
showMsgPanel();
playSound();
};
websocket.onerror = function(e) {};
websocket.onclose = function(e) {
websocket = null;
clearMessage();
hideMsgPanel();
};
}
},
sendMessage: function() {
elements.txtMsg.focus();
if (websocket != null && websocket.readyState == 1) {
var input = elements.txtMsg.value.trim();
if (input == '') { return; }
elements.txtMsg.value = '';
var message = { messageType: 'MESSAGE', message: input };
// Send a message through the web-socket
websocket.send(JSON.stringify(message));
}
},
login_keyup: function(e) { if (e.keyCode == 13) { this.login(); } },
sendMessage_keyup: function(e) { if (e.keyCode == 13) { this.sendMessage(); } },
logout: function() {
if (websocket != null && websocket.readyState == 1) { websocket.close();}
},
initiate: function(e) {
elements = e;
elements.txtLogin.focus();
}
}
};

Refreshing div inside HTML without any PHP?

Good afternoon !
The idea behind my project is to send made-by-hand logs to a webpage so that I don't have to rely solely on the Serial Monitor.
I am sending Strings from ESP32 to a webpage that is hosted by the same ESP32.
To do that I am using ESPAsyncWebServer library that let's me use placeholders inside the HTML. The ESP then uses:
String processor(const String& var)
and
server.on("/logs", HTTP_GET, [](AsyncWebServerRequest* request){
request->send(SPIFFS, "/events.html", "text/html", false, processor);
});
to replace the placeholder it founds with whatever piece of data I want.
I am using a circular buffer so that I don't end up using all the memory.
I googled how should I refresh a div inside a html and everywhere I looked there was a .load('file.php'). I don't have any .php files for my project.
The question is what do I load instead of that php file ?
Loading the same .html page did not work.
events.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href = "master.css">
<title>Events Log</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script>
$(document).ready( function(){
$('#big-box').load('events.html');
refresh();
});
function refresh()
{
setTimeout( function() {
$('#big-box').fadeOut('slow').load('events.html').fadeIn('slow');
refresh();
}, 2000);
}
</script>
</head>
<body>
<div id="big-box">
<div class="textbox">%PLACEHOLDER_1%</div>
<div class="textbox">%PLACEHOLDER_2%</div>
<div class="textbox">%PLACEHOLDER_3%</div>
<div class="textbox">%PLACEHOLDER_4%</div>
<div class="textbox">%PLACEHOLDER_5%</div>
</div>
</body>
main.cpp
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <cstdio>
#include <memory>
#include <mutex>
void logOutput(String string);
//---------- Circular Buffer
template <class T>
class circular_buffer {
public:
explicit circular_buffer(size_t size) :
buf_(std::unique_ptr<T[]>(new T[size])),
max_size_(size)
{
}
void put(T item){
std::lock_guard<std::mutex> lock(mutex_);
buf_[head_] = item;
if(full_){
tail_ = (tail_ + 1) % max_size_;
}
head_ = (head_ + 1) % max_size_;
full_ = head_ == tail_;
}
T get() {
std::lock_guard<std::mutex> lock(mutex_);
if(empty()) {
return T();
}
//Read data and advance the tail (we now have a free space)
auto val = buf_[tail_];
full_ = false;
tail_ = (tail_ + 1) % max_size_;
return val;
}
T get2() {
std::lock_guard<std::mutex> lock(mutex_);
if(empty()) {
return T();
}
auto val = buf_[tail_];
return val;
}
void reset() {
std::lock_guard<std::mutex> lock(mutex_);
head_ = tail_;
full_ = false;
}
bool empty() const {
//if head and tail are equal, we are empty
return (!full_ && (head_ == tail_));
}
bool full() const {
//If tail is ahead the head by 1, we are full
return full_;
}
size_t capacity() const {
return max_size_;
}
size_t size() const {
size_t size = max_size_;
if(!full_) {
if(head_ >= tail_) {
size = head_ - tail_;
} else {
size = max_size_ + head_ - tail_;
}
}
return size;
}
private:
std::mutex mutex_;
std::unique_ptr<T[]> buf_;
size_t head_ = 0;
size_t tail_ = 0;
const size_t max_size_;
bool full_ = 0;
}; //---------- Circular Buffer
circular_buffer<String> circle(20);
void logOutput(String string) {
delay(2000);
circle.put(string);
Serial.println(string);
}
AsyncWebServer server(80);
const char* ssid = "metrici.ro";
const char* password = "cocoscocos";
String processor(const String& var) {
if(var == "PLACEHOLDER_1"){
return circle.get();
} else if(var == "PLACEHOLDER_2") {
return circle.get();
} else if(var == "PLACEHOLDER_3") {
return circle.get();
} else if(var == "PLACEHOLDER_4") {
return circle.get();
} else if(var == "PLACEHOLDER_5") {
return circle.get();
}
return String();
}
void setup() {
Serial.begin(115200);
delay(2000);
if(!SPIFFS.begin(true)) {
logOutput("ERROR ! SPIFFS file system was not mounted. Reformatting !");
}
WiFi.begin(ssid, password);
delay(1000);
int k = 0;
while(WiFi.status() != WL_CONNECTED && k<20) {
delay(1000);
k++;
logOutput("Connecting to WiFi");
}
if(WiFi.status() == WL_CONNECTED) {
logOutput((String)"Connected to: " + ssid + " with IP: " + WiFi.localIP().toString());
} else {
logOutput("Couldn't connect to WiFi ! Restarting in 5 seconds");
delay(5000);
ESP.restart();
}
server.on("/logs", HTTP_GET, [](AsyncWebServerRequest* request){
request->send(SPIFFS, "/events.html", "text/html", false, processor);
});
server.on("/master.css", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/master.css", "text/css");
});
server.on("/back-image.jpg", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/back-image.jpg", "image/jpeg");
});
server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/logo.png", "image/png");
});
server.begin();
delay(5000);
logOutput("After server.begin()");
for(int i = 1; i<=10;i++){
logOutput((String)"Linia " + i);
}
}
void loop() {
logOutput("Beginning the loop()");
logOutput("\n");
delay(10000);
}
TL;DR The ESP server doesn't serve the /jquery-1.9.0.min.js and /events.html files that the original HTML references. Read on for details.
When $('#big-box').load('events.html') code executes, the browser makes a HTTP GET call in background to your ESP server, at path /event.html. The requests on that path doesn't seem to be handled on ESP side. To handle requests on that path, you'd need something like this:
server.on('/event.html`, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/events-log.html", "text/html", false, processor);
})`.
Additionally, you'd need to create events-log.html file with following content (basically everything that big-box div contained):
<div class="textbox">%PLACEHOLDER_1%</div>
<div class="textbox">%PLACEHOLDER_2%</div>
<div class="textbox">%PLACEHOLDER_3%</div>
<div class="textbox">%PLACEHOLDER_4%</div>
<div class="textbox">%PLACEHOLDER_5%</div>
Also note, that the jquery-1.9.0.min.js file that you included in your HTML file (using script tag) wouldn't be loaded for same reason. The browser will try to send a HTTP GET request to /jquery-1.9.0.min.js, and since request on that path isn't handled, browser will get 404 error.
If the computer on which you are accessing this page has internet access, then you can load jQuery from CDN by changing your script tag to following snippet. If the machine doesn't have internet access then you'd need to download the jQuery file, save it to SPIFFS, and serve it in same manner as the other files.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

Javascript alert in code behind

I need to call Javascript alert function in c# method if web service is not available. I am using as.net core and webapi for webservice.
Here is the code
public List<EmployeeModel> GetEmployeeByEmpNo(string empNo)
{
try
{
string Baseurl = sys_ser.getApiURL();
EmployeeModel EmpInfo = new EmployeeModel();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync("api/Values/GetEmployeeByEmpNo/" + empNo).Result;
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
var empobjList = JsonConvert.DeserializeObject<List<EmployeeModel>>(EmpResponse);
//var EmpObj = empobjList[0];
if (empobjList != null)
{
return empobjList;
}
}
}
}
catch(Exception ex)
{
//<Srcript> alert('WebService is not available' + ex.message)</>
}
return null;
}
If AJAX isn't an option, you can pass a flag to tell the client to create the window:
Controller:
return View("Index", (object)errorDetails);
View:
#model string
<!--Your HTML-->
#if (!string.IsNullOrEmpty(Model)
{
<script type="text/javascript">
alert(Model);
</script>
}

Not able to Json response from rest server

Im trying to parse a Json response from a rest server using JavaScript and display the data.
The rest server works fine its just that i cant parse the data. I have looked at dozens of examples and from my understanding the code looks fine.
This is my first attempt at learning Ajax and if i fix this i can continue with my project.
This is the response
{"id":"1","author":"Bill Burke","title":"RESTful Java with JAX-RS","year":"2009"}
This is the server
#Path("/books") // JAX-RS annotation
public class BookResource {
#GET // JAX-RS annotation
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
#Path("/{bookId}")
public Book getBook(#PathParam("bookId") String id) {
return BookDao.instance.getBook(Integer.parseInt(id));
}
}
This is the client
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script type="text/javascript">
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhr = false;
}
}
}
return xhr;
}
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
parseJ(request);
};
request.open("GET", file, true);
request.send(null);
}
}
function parseJ(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
var obj = JSON.parse(request.responseText);
document.getElementById("details").innerHTML = obj.id + " " + obj.author + " "
+ obj.title + " " + obj.year;
}
}
}
</script>
</head>
<body>
<a
href="http://localhost:8080/Distributed_REST_booksServer/rest/books/1"
onclick="grabFile(this.href); return false;">Book 1</a>
<br>
<div id="details"></div>
</body>
</html>
html console error
html console error after modification
Your server is returning XML, try to force it as JSON and maybe add an accept header to the request from the client.

Understand 304 response - not modified?

I am running the following script on the client-side and the script is failing to update, when there is change in the database. I debugged the script using DevTools and discovered my Jquery scripts are responding back as "304 not modified". Does this issue, indicate why the client-side content is failing to update.
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery-1.6.4.min.js"></script>
<script src="../Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.NotificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (role, descrip) {
// Add the message to the page.
$('#spanNewMessages').text(role);
$('#spanNewCircles').text(descrip);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications();
alert("Notifications have been sent.");
}).fail(function (e) {
alert(e);
});
//$.connection.hub.start();
});
</script>
<h1>New Notifications</h1>
<div>
<br />
<b>New <span id="spanNewMessages"></span> = role.</b><br />
<b>New <span id="spanNewCircles"></span> = descrip.</b><br />
</div>
Hub Class:
[HubName("NotificationHub")]
public class notificationHub : Hub
{
string role = "";
string descrip = "";
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
{
string query = "SELECT top 1 [role],[description] FROM [dbo].[User] order by uploadDate desc";
connection.Open();
SqlDependency.Start(GetConnectionString());
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
role = dt.Rows[0]["role"].ToString();
descrip = dt.Rows[0]["description"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
Clients.All.RecieveNotification(role, descrip);
}
[HubMethodName("onStatusChanged")]
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
{
notificationHub nHub = new notificationHub();
nHub.SendNotifications();
}
}
Please advice. Thank you.

Categories