asp.net mvc -view displaying real-time progress status - c#

I want to display progress on my screen/page/view just as happens in console. So when i click install button, my "textarea" control should start displaying progress like
connecting to database
connection successful
running script a.sql
running script b.sql
operation complete
connection closed
Is textarea the correct control for this purpose?
it Seems like there will be too many trips from server to the client just to write the progress on screen how can i minimize it?

To be able to do this easily, you can use SignalR which simplify all the hassle of which underlying technology to be used based on the version of the browser it will choose the best communication protocol (WebSocket, LongPolling..etc).
Behind SignalR, one of the underlying used technologies is websockets, it doesn't send anything except keep an open full duplex channels between server and client, in case any update in the server it will push this update to the client. most popular sites use websockets for keeping open channels between server and client.
SignalR uses actually websockets however it will downgrade to use long polling for example in case of old browsers that don't support websocket's connection upgrades.
You have the option to use the websockets directly in case you are assured your clients use new browsers.
One last thing Stackoverflow as a big and heavy loaded site uses websockets to update once there is a new answer or comment for example.

The general approach for this is just sending an ajax request every second or so and asking for an update from the server.
<div>
<pre id="status">
</pre>
</div>
setInterval(function () {
$.ajax("/getUpdate?someParam=1234").then(function (result) {
// result is whatever JSON object you send from the server
$("#status").innerText = result.someProp;
});
}, 1000);
It might look something like the above. Note that it's doing a request every second and storing the message from the server in the pre element.

Related

ASP.Net Server Side code, does it keep running after user logged out? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
To give this question context we have an ASP.Net MVC Project which requires you to be authenticated to use the system (typical saas product). The project includes an inactivity timer which will log the user out if they leave the screen alone for too long. The project is an SPA type project and Web API is used to get/post relevant data.
I am currently having to develop a routine that archives a potentially huge amount of data and the process itself is fine. What I'm not sure of is once the process is started, a post is sent to web api and the server side code starts running, does it continue to run if the inactivity timeout occurs or the user logs out manually for some reason?
I assume it would but I don't like to rely on assumptions.
EDIT: For example
For below comments/answers. Screen will have a list of tickboxes for the data they wish to archive so is not a set list of data so this project does need to process the task.
The following code is on the client side when running (checks etc omitted and data variable contains all true/false values for ticks):
self.Running = true;
self.showProgress();
http.ajaxRequest("post", "/api/archive/runarchive", data)
.done(function () {
self.Running = false;
})
.fail(function () {
self.Running = false;
app.showMessage("You do not have permission to perform this action!");
});
For reference the showProgress function used to pick up progress to display on screen. This is also run when accessing the screen in case an archive process is still running it can be displayed:
self.showProgress = function () {
http.ajaxRequest("get", "/api/archive/getarchiveprocess")
.done(function (result) {
if (result.ID == -1) {
$("#progressBar").hide();
$("#btnArchive").show();
if (self.Running) setTimeout(self.showProgress, 2000);
else app.showMessage("The Archive Process has finished.");
}
else {
$("#progressBar").show();
$("#btnArchive").hide();
$("#progressBarInner").width(result.Progress + '%');
$("#progressBarInner").attr("data-original-title", result.Progress + '%');
setTimeout(self.showProgress, 2000);
}
});
};
Server Side:
[HttpPost]
public void RunArchive(dynamic data)
{
// Add table row entry for the archive process for reference and progress
// Check each tick and update tables/fields etc
// Code omitted as very long and not needed for example
// table row for reference edited during checks for showProgress function
}
So basically I'm asking if the RunArchive() function on the controller will keep running until it's finished despite user logging off and being unauthenticated in some way. I'm aware any IIS, App Pool refresh etc would.
It sounds like web api is the one doing the heavy work and once that starts it will continue to run regardless of what happens on the UI side of things.
This being said, there is a timeout for webapi requests that you can control in web.config.
You might want to consider another alternative. Whenever you're talking about heavy processing tasks, you're better offloading those to another service.
Your API is supposed to be responsive and accessible by your users and it needs to respond fast to allow for a better experience. If you get 100 users doing heavy work, your API will basically crumble.
The API could simply send commands to a queue of stuff that needs to be run and another service can pick them up and execute them. This keeps your API lightweight while the work is still being done.
You're talking about archiving which probably involves a database and there is no reason why you can't have something else do that job.
You could keep track of jobs in the database, you could build a table which holds statuses and once a job is done, the external service changes the status in the database and your UI can then show the result.
So the API could work like this:
add message to queue
add job details to db with status of "new" for example and a unique id which allows the queue item to be linked to this record.
Service B picks up the job from the queue and updates status in db to "running".
Job finishes and Service B updates status to "complete".
the UI reflects these statuses so the users know what's going on.
Something like this should would make for a better user experience I would think.
Feel free to change whatever doesn't make sense, it's a bit hard to give suggestions when you don't know the details of what needs to be done.
This Service B could be a windows service for example or whatever else you want that can do the job. The user permissions come into play in the beginning only, a work item would be added to the queue only if the user has the permission to initiate that. This gives you the certainty that only authorized jobs are added.
After that, Service B won't care about user permissions and will do the job to the end irrespective about users being logged in or not.
This is largely guess work at this point, but you should be able to get an idea of how to do this.
If you have more specific requirements you should add those to the initial question.
Even if the process isn't killed by the user logging out, you also need to consider that IIS can recycle app pools, and by default is set to do so once a day, as well as on memory contention, either of which will kill your long running process.
I would highly recommend you check out Hangfire.io, which is designed to help with long running processes in ASP.Net sites.

C# windows service subscribed to webserver

I'm working on an intranet website.
All users should get desktop popups from the webserver whenever something new is posted on the website.
I was looking to make my own windows service that would subscribe to the server ( Making use of something like SignalR ) and then this service would show a simple popup notifying the user whenever the server sends out a message.
But instead of building this myself i was wondering if something like this isn't already out there. I've been looking around a bit but couldn't find anything.
I'm mainly a web developer and have never built a windows service or C# desktop application so i would prefer using some existing code.
Does anyone know of such a thing ?
For building a Windows Service try Top Shelf: http://docs.topshelf-project.com/en/latest/
In general it is easy as one, two, three...
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer(1000) {AutoReset = true};
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
public class Program
{
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name=> new TownCrier());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("Stuff");
x.SetServiceName("Stuff");
});
}
}
I'm working on an intranet website. All users should get desktop
popups from the webserver whenever something new is posted on the
website.
using timer is not a good technique over here as updates are not guaranteed in particular interval or session .but you can take that as an option based on the need.
I was looking to make my own windows service that would subscribe to
the server ( Making use of something like SignalR ) and then this
service would show a simple popup notifying the user whenever the
server sends out a message.
Yes exactly like a chat application that would frequently have messages and users get a pop up.ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.
But instead of building this myself i was wondering if something like
this isn't already out there. I've been looking around a bit but
couldn't find anything.
References for SignalR Link1,Link2,Link3
I'm mainly a web developer and have never built a windows service or
C# desktop application so i would prefer using some existing code.
Making C# desktop or windows service is not a big deal as you already are a programmer.Some existing codes for updations pop up is here.
for the signalr Server side, I would suggest you use a C# winform.
for the client side, you can use JavaScript inside any html file to 'receive' the message from the signalr Server, then you can popup an alert message or whatever you want, however, in this case you have to make sure the users are browsing that html file in a browser, otherwise the message won't be received.
there's no ready code since signalr support different types of servers as well as different types of clients, I believe you need to write your own code. Actually Signalr is quite easy to use, write your own code may be faster than using the others.
This question: SignalR Chat App in WinForm With Remote Clients looks like it might point you inthe right direction. Specifically this article:
https://damienbod.wordpress.com/2013/11/01/signalr-messaging-with-console-server-and-client-web-client-wpf-client/
you could probably use DesktopToast: https://github.com/emoacht/DesktopToast
or Growl: http://www.growlforwindows.com/

Detect Internet Connectivity on client machine

I have this web application (MVC using C#) that serves like an advertisement in my client's office. My client will open this "advertisement page" and display it on a big screen to their customers.
What happen is, every 30 minutes or so, the page will automatically refresh to fetch latest data from the database, however, they are using WIFI to connect to our server and sometimes the connection is very slow (or lost connection completely). My client requested me to write a code to prevent the page from refreshing if the connectivity is bad or no internet connection. (They do not want to show "No Internet Connection" on their advertisement TV)
I know I cannot do anything from the server side code because it is the client's machine that want to detect the internet connection, so leaving client side code as the only option. I am not good at this, can anyone help me out?
I'd suggest a "ping" sent via ajax:
var timeStart= new Date().getTime();
$.ajax({
url:"url-to-ping-response-file",
success:function(){
var timeNow = new Date().getTime();
var ping = timeNow - timeStart;
//less than one second
if(ping < 1000){
window.location.reload();
}
}
});
You can use the Circuit Breaker Pattern to gracefully handle intermittently connected environments.
Here are 2 open source JavaScript implementations. I have never used either of them, so I cannot attest to their quality.
https://github.com/yammer/circuit-breaker-js
https://github.com/mweagle/circuit-breaker
You can also make use of
if (navigator.onLine) {
location.reload();
}
This will not detect slow internet. Now, I don't understand your web layout but for sites that I work on I tend to get HTML content and DATA as separate calls. I do this with a MVVM/MVC pattern which is worth learning. I use angularjs it is very awesome.
Now.. you can also use good old jQuery to replace the content have a read of this Replace HTML page with contents retrieved via AJAX you could couple this with the .onLine check.
http://www.w3schools.com/jsref/prop_nav_online.asp

Ensuring RavenDB 3.0 FileSystem Synchronization Before Action

Here is the setup:
There are 2 Servers : one at the client site and one on another server
The connection between the two of them is not always on.
I have to have code that replicates the functionality from the Server UI: FileSystem > Status > "Sync Now"
I have to be able to watch the process to ensure that it completes without conflicts before moving I move on the next step.
Can anyone point me to the proper classes in the Raven Client Library to do this? Examples would be greatly appreciated.
You are looking for:
DestinationSyncResult[] syncResults = await store.AsyncFilesCommands.Synchronization.SynchronizeAsync();
This will force your server to push all changes to destinations and return all the details about processed files and errors if happened any. Investigate also more methods exposed by IAsyncFilesSynchronizationCommands:
store.AsyncFilesCommands.Synchronization.XXXXX
You can also use the Changes API mechanism to be notified about server activity. It works the same way like for RavenDB databases. For example:
store.Changes().Where(x => x.Direction == SynchronizationDirection.Outgoing).ForSynchronization().Subscribe(x => { });

A not stateless Socket solution for NodeJS

I have to built a Client/Server application where the server side is just an application that passes data from one client to the other.
The client will be written in C# and I want to write the server in NodeJS, if that's possible. I'll try to explain the idea behind this.
It's best to explain this if you see this application as a 1vs1 game. So multiple clients can connect to an Async server. One client will be matched with another client as in a Player1 / Player2 context.
Player1 can make a "move". A POCO will be converted to a JSON format for example. That will then be send to the server and the server should know to what opponent (Player2) it should sent the data. Then in return Player2 can make a move and then new data will be send back through the server back to Player1.
So the server needs to have a list of all the connected players/clients. So it can keep track of what player play vs who and what scores they have etc. Basically, a stateless environment.
I've been thinking about writting the server in C# with the SocketAsyncEventArgs class. But since NodeJS/Socket.IO is already an optimized lib, that would save time if I could do it in that.
I just need to know if it's possible to do this in NodeJS. Or should I stick to a C# server?
Okey,
I argue that it is possible if you use something like SocketIO4Net.Client at your C# side to open connection to your node.js server.
From the docs:
SocketIO4Net.Client can interact with Socket.IO instances in a very
similar manner as Socket.IO JavaScript clients. This project aims to
fill the JavaScript client and C# client gap for Socket.IO, and retain
a very similar application experience.
And for the purpose of storing player lists etc. at server, it is easy. You define javascript object just as players where you add your connected clients and use for example socket.id as identifier.
// Players currently at server
var players = {};
you do this usually by listening socket connection event, for example:
... somewhere in your code ...
var io = require('socket.io').listen(httpServer);
... somewhere in your code ...
// run on new client connection..
io.sockets.on("connection", function (socket) {
// adding to list of players you have in your server
// Player can be your own declared class as you like it to be
players[socket.id] = new Player({
nickname: "playerNameExample"
});
});
However, if your game is more like match-making 1vs1 it would be worth to consider that you add always your separate playing partners to different rooms in server. So exchanging messages travels only between relevant participants. See socket.io rooms
As for the resources where to go next: best choice is to just google "multiplayer game with socket.io" which will give wide variety of results. Just as this: Building-multiplayer-games-with-nodejs if you are completely new to node.js googling hello world with node.js might be better to do first.
Due note: If you don't know the basics and haven't tried programming anything with node.js you are not ready to make working multiplayer game, advance step by step.! ( and yes I am looking this now from game perspective as you instructed but behavior of games can be applied to many apps as well ). Cheers.

Categories