Using signalR to update Winforms UI - asynchronous

I have a form that was created on it's own UI thread running in the system tray which I need to manipulate with a signalR connection from the server which I believe to be running on a background thread. I'm aware of the need to invoke controls when not accessing them from their UI thread. I am able to manipulate (make popup in my case) using the following code that is called on form load but would like a sanity check as I'm fairly new to async:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var backgroundTask = connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
var uiTask = backgroundTask.ContinueWith(t =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
}, uiThreadScheduler);
});
}
Does this look OK? It's working on my local machine but this has the potential to be rolled out on every user machine in our business and I need to get it right.

Technically you should hook up to all notifications (using On<T>) before you Start listening. As far as your async work I'm not quite sure what you were trying to do, but for some reason your chaining the notification to your UI in On<T> to the backgroundTask variable which is the Task that was returned to you by the call to Start. There's no reason for that to be involved there.
So this is probably what you want:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
Task.Factory.StartNew(
() =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
},
CancellationToken.None,
TaskCreationOptions.None,
uiTaskScheduler);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
}

Related

TypeOrm - Can't create a connection outside of main function

I have a problem with typeorm, function createConnection works only in index file, if I try to run it in any other file it gets stuck waiting for connection.
export async function saveKU(data: KUData) {
console.log("Foo");
let connection = await createConnection(typeormConfig);
console.log("Received!: " + connection);
const user = connection
.getRepository(KU)
.createQueryBuilder("ku")
.where("ku.ku_number = :ku_number", { ku_number: "54645" })
.getOne();
console.log(user);
}
Message received never gets logged, but then if I run the exact same script in the main function
const main = async () => {
// quit application when all windows are closed
app.on("window-all-closed", () => {
// on macOS it is common for applications to stay open until the user explicitly quits
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// on macOS it is common to re-create a window even after all windows have been closed
if (mainWindow === null) {
mainWindow = createMainWindow();
}
});
app.allowRendererProcessReuse = true;
// create main BrowserWindow when electron is ready
app.on("ready", () => {
mainWindow = createMainWindow();
});
let connection = await createConnection(typeormConfig);
console.log("Received!: " + connection);
const user = connection
.getRepository(KU)
.createQueryBuilder("ku")
.where("ku.ku_number = :ku_number", { ku_number: "54645" })
.getOne();
console.log(user);
};
Everything works fine, no error is showing up in both cases, I have no idea what the problem could be, the closest to my example is the following link: https://senorihl.github.io/2019/03/electron-typescript-react-typeorm/
Except that I'm using electron-webpack and creating connections in an index.tsx file doesn't work for me, but rather index.ts

Can I set up 2 SignalR connections?

I have a basic chat app set up like so:
$(function () {
// Set up references for other functions to call
chatConnection = $.connection.chatHub;
// Set up callbacks before starting server connection
chatConnection.client.addNewMessageToPage = function (name, message) {
var prettyMessage = name + ':' + message;
$('#chatHistory').append(prettyMessage);
$("#chatHistory").animate({ scrollTop: $('#chatHistory').prop("scrollHeight") }, 10);
};
// Start up connection to server, set up events
$.connection.hub.start().done(function () {
$('#sendChatButton').click(function () {
// Call the Send method on the hub.
chatConnection.server.sendMessage($('#displayName').val(), $('#chatBox').val());
// Clear text box and reset focus for next comment.
$('#chatBox').val('').focus();
});
});
});
This calls into my ChatHub.cs server side and I am getting and passing back messages as you would expect.
public void SendMessage(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
Now I want to add functionality. I Have a new class almost identical to my ChatHub called "GameHub" and it's job is to process moves instead of processing chat. So far I have something like this:
$(function () {
// Set up references for other functions to call
chatConnection = $.connection.chatHub;
gameConnection = $.connection.gameHub;
// Set up callbacks before starting server connection
chatConnection.client.addNewMessageToPage = function (name, message) {
var prettyMessage = name + ':' + message;
$('#chatHistory').append(prettyMessage);
$("#chatHistory").animate({ scrollTop: $('#chatHistory').prop("scrollHeight") }, 10);
};
gameConnection.client.receiveMove = function (name, move){
alert(name + ' played ' + move);
};
// Start up connection to server, set up events
$.connection.hub.start().done(function () {
$('#sendChatButton').click(function () {
// Call the Send method on the hub.
chatConnection.server.sendMessage($('#displayName').val(), $('#chatBox').val());
// Clear text box and reset focus for next comment.
$('#chatBox').val('').focus();
});
$('#sendMoveButton').click(function () {
gameConnection.server.sendMove(getMove());
});
});
});
but nothing is making it to the server. Is this because I don't have it set up correct? Can signalR even support 2 hubs or should it be a single hub and "spoke" out from there to my 2 different functional areas?
You can but given that there is no performance difference it's simpler to have those functions in one hub. All data will hit all hubs as they all share the same connection.
As documented here.
You can check, since it's not provided, your game hub and method to ensure you have them named and cased properly on the server side. Possible issues...

App Maker: Sending Email, client script to server script function not working. Failed due to illegal value in property: a

I am new to AppMaker but I have developer experience.
The application is a Project Tracker Application
What I expect to happen: When creating a project the user uses a User Picker to select the users associated with that project. When the project is created I want to email the users associated with that project.
The issue: On clicking the Add button addProject(addButton) client script function is called.
Inside this function sendEmailToAssignees(project, assignees) is called which should reach out to the Server script and run the notifyAboutProjectCreated(project, assignees) but that is not happening.
Things to know: With logging I never reach 'Trying to send email' so I seem to never reach my server script. Also, On client script when I comment out sendEmailToAssignees function everything runs smooth. I have looked at this documentation as a resource so I feel my implementation is okay. https://developers.google.com/appmaker/scripting/client#client_script_examples
The final error message I get is:
Failed due to illegal value in property: a at addProject
(AddProject:110:24) at
AddProject.Container.PanelAddProject.Form1.Spring.ButtonAdd.onClick:1:1
Am I missing something here? Any help would be greatly appreciated. Thank you!
Client Script
function sendEmailToAssignees(project, assignees) {
google.script.run
.withSuccessHandler(function() {
console.log('Sending Email Success');
}).withFailureHandler(function(err) {
console.log('Error Sending Email: ' + JSON.stringify(err));
})
.notifyAboutProjectCreated(project, assignees);
}
function addProject(addButton) {
if (!addButton.root.validate()) {
return;
}
addButton.datasource.createItem(function(record) {
var page = app.pages.AddProject;
var pageWidgets = page.descendants;
var trainees = pageWidgets.AssigneesGrid.datasource.items;
var traineesEmails = trainees.map(function(trainee) {
return trainee.PrimaryEmail;
});
record.Assignee = traineesEmails.toString();
var assignees = traineesEmails.toString();
var project = record;
updateAllProjects(record);
console.log('update all projects done');
sendEmailToAssignees(project, assignees);
console.log('Send Email done');
if (app.currentPage !== app.pages.ViewProject) {
return;
}
gotoViewProjectPageByKey(record._key, true);
});
gotoViewProjectPageByParams();
}
Server Script
function notifyAboutProjectCreated(project, assignees) {
console.log('Trying to send email');
if (!project) {
return;
}
var settings = getAppSettingsRecord_()[0];
if (!settings.EnableEmailNotifications) {
return;
}
var data = {
appUrl: settings.AppUrl,
assignee: project.Assignee,
owner: project.Owner,
startDate: project.StartDate,
endDate: project.EndDate,
jobType: project.Type,
jobId: project.Id
};
// Email Subject
var subjectTemplate = HtmlService.createTemplate(settings.NotificationEmailSubjectJob);
subjectTemplate.data = data;
var subject = subjectTemplate.evaluate().getContent();
// Email Body
var emailTemplate =
HtmlService.createTemplate(settings.NotificationEmailBodyJob);
emailTemplate.data = data;
var htmlBody = emailTemplate.evaluate().getContent();
console.log('About to send email to:', assignees);
sendEmail_(null, assignees, subject, htmlBody);
}
The reason you are getting this error is because you are trying to pass the client "project record" to the server. If you need to access the project, then pass the record key to the server and then access the record on the server using the key.
CLIENT:
function sendEmailToAssignees(project, assignees) {
var projectKey = project._key;
google.script.run
.withSuccessHandler(function() {
console.log('Sending Email Success');
}).withFailureHandler(function(err) {
console.log('Error Sending Email: ' + JSON.stringify(err));
})
.notifyAboutProjectCreated(projectKey , assignees);
}
SERVER:
function notifyAboutProjectCreated(projectKey, assignees) {
console.log('Trying to send email');
var project = app.models.<PROJECTSMODEL>.getRecord(projectKey);
if (!project) {
return;
}
//Rest of the logic
}
The project record object in the client is not the same as the project record object in the server; hence the ilegal property value error.

.NET Core SignalR, Server timeoute / Reconnect issue

I have a SignalR hub written in my MVC solution, with a Javascript client connecting from the view.
The point of the connection is to receive changes for a wallboard from the server. This has to happen almost instantly and requires a lifetime connection, since the webpage is running on a screen without direct pc access.
So far the SignalR connection works for a couple of hours before it gives error.
The error I get is
Error: Connection disconnected with error 'Error: Server timeout elapsed without receiving a message form the server.'.
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Warning: Error from HTTP request. 0:
Error: Failed to complete negotiation with the server: Error
Error: Failed to start the connection: Error
Uncaught (in promise) Error
at new HttpError (singlar.js:1436)
at XMLHttpRequest.xhr.onerror (singalr.js:1583)
My client code
let connection = new signalR.HubConnectionBuilder()
.withUrl("/wbHub")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start().then(function () {
connection.invoke("GetAllWallboards").then(function (wallboard) {
for (var i = 0; i < wallboard.length; i++) {
displayWallboard(wallboard[i]);
}
startStreaming();
})
})
connection.onclose(function () {
connection.start().then(function () {
startStreaming();
})
})
function startStreaming() {
connection.stream("StreamWallboards").subscribe({
close: false,
next: displayWallboard
});
}
Hub Code:
public class WallboardHub : Hub
{
private readonly WallboardTicker _WallboardTicker;
public WallboardHub(WallboardTicker wallboardTicker)
{
_WallboardTicker = wallboardTicker;
}
public IEnumerable<Wallboard> GetAllWallboards()
{
return _WallboardTicker.GetAllWallboards();
}
public ChannelReader<Wallboard> StreamWallboards()
{
return _WallboardTicker.StreamWallboards().AsChannelReader(10);
}
public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users");
await base.OnDisconnectedAsync(exception);
}
}
Question 1: Is the way I handle reconnecting correct? From the error it feels like the .onclose works, but that it only tries one time? Is there anyway to try for x min before showing error?
Question 2: Reloading the website makes the connection work again, is there potential anyway to refresh the browser on signalR connection error?
I have the same issue (Question 1), and i resolve with this:
const connection = new SignalR.HubConnectionBuilder()
.withUrl("/hub")
.configureLogging(SignalR.LogLevel.Information)
.build();
connect(connection);
async function connect(conn){
conn.start().catch( e => {
sleep(5000);
console.log("Reconnecting Socket");
connect(conn);
}
)
}
connection.onclose(function (e) {
connect(connection);
});
async function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec));
}
Every 5 seconds tries to reconnect, but i don't know if this is the right way to do this.
ASP.NET Core 2.1 (current LTS release) with the corresponding SignalR release doesn't seem to have some integrated reconnecting method avaliable. The code from #Shidarg doesn't work for me, it calls the reconnect method in a infinitive loop crashiny my browser. I also like the async/await syntax from C# more, so I updated it:
let reconnectWaitTime = 5000
let paramStr = '?myCustomArg=true'
let client = new signalR.HubConnectionBuilder()
.withUrl("/overviewHub" + paramStr)
.build();
client.onclose(async () => {
console.warn(`WS connection closed, try reconnecting with loop interval ${reconnectWaitTime}`)
tryReconnect(client)
})
await tryReconnect(client)
async function tryReconnect(client) {
try {
let started = await client.start()
console.log('WS client connected!')
// Here i'm initializing my services, e.g. fetch history of a chat when connection got established
return started;
} catch (e) {
await new Promise(resolve => setTimeout(resolve, reconnectWaitTime));
return await tryReconnect(client)
}
}
But for ASP.NET Core 3 they included a reconnecting method:
let client = new signalR.HubConnectionBuilder()
.withUrl("/myHub")
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Information)
.build();
Per default it try three reconnects: First after 2 seconds, second after 10 seconds and the last about 30 seconds. This could be modificated by passing the intervalls as array parameter:
.withAutomaticReconnect([5000, 1500, 50000, null])
This example re-trys after 5s, 15s and 50s. The last null param tell SignalR to stop re-trying. More information could be found here: https://www.jerriepelser.com/blog/automatic-reconnects-signalr/
Configuring automatic reconnects only requires a call to withAutomaticReconnect on the HubConnectionBuilder. Here is what my JavaScript code looks like for configuring my connection:
connection = new signalR.HubConnectionBuilder()
.withUrl("/publish-document-job-progress")
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Information)
.build();
You can configure the backoff period by passing an array of retry delays to the call to withAutomaticReconnect(). The default for this is [0, 2000, 10000, 30000, null]. The null value tells SignalR to stop trying. So, for example, if I wanted it to retry at 0, 1 second and 5 seconds, I can configure my HubConnectionBuilder as follows:
connection = new signalR.HubConnectionBuilder()
.withUrl("/publish-document-job-progress")
.withAutomaticReconnect([0, 1000, 5000, null])
.configureLogging(signalR.LogLevel.Information)
.build();

pushPlugin notification on the server and front-en

does this get triggered again from the server containing a message?
"ecb":"window.onNotificationGCM"
I have this set up on the server
device_tokens = [], //create array for storing device tokens
retry_times = 4, //the number of times to retry sending the message if it failed
sender = new gcm.Sender('AIzaSyDpA0b2smrKyDUSaP0Cmz9hz4cQ19Rxn7U'), //create a new sender
message = new gcm.Message(); //create a new message
message.addData('title', 'Open Circles');
message.addData('message', req.query.message);
message.addData('sound', 'notification');
message.collapseKey = 'testing'; //grouping messages
message.delayWhileIdle = true; //delay sending while receiving device is offline
message.timeToLive = 3; //the number of seconds to keep the message on the server if the device is offline
device_tokens.push(val.deviceToken);
sender.send(message, device_tokens, retry_times, function(result){
console.log(result);
console.log('push sent to: ' + val.deviceToken);
});
So what I want to know is, once a server call is made will it trigger the notification on the front. What am I missing about this system?
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (event.foreground) {
console.log('INLINE NOTIFICATION');
var my_media = new Media("/android_asset/www/" + event.soundname);
my_media.play();
} else {
if (event.coldstart) {
console.log('COLDSTART NOTIFICATION');
} else {
console.log('BACKGROUND NOTIFICATION');
}
}
navigator.notification.alert(event.payload.message);
console.log('MESSAGE -> MSG: ' + event.payload.message);
//Only works for GCM
console.log('MESSAGE -> MSGCNT: ' + event.payload.msgcnt);
//Only works on Amazon Fire OS
console.log('MESSAGE -> TIME: ' + event.payload.timeStamp);
break;
case 'error':
console.log('ERROR -> MSG:' + event.msg);
break;
default:
console.log('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
};
return {
register: function () {
var q = $q.defer();
if(ionic.Platform.isAndroid()){
pushNotification.register(
successHandler,
errorHandler,
{
"senderID":"346007849782",
"ecb":"window.onNotificationGCM"
}
);
}else{
pushNotification.register(
tokenHandler,
errorHandler,
{
"badge":"true",
"sound":"true",
"alert":"true",
"ecb":"window.onNotificationAPN"
}
);
}
return q.promise;
}
}
update. Eventually my server spit back this: TypeError: Cannot read property 'processIncomingMessage' of undefined
It seems my google ID was not working. I created a new one and now it's sending push requests.

Resources