I have an ASP.NET application and a C# application hosting a WebBrowser. The ASP.NET application is run through the C# application.
I am in need of notifying the C# application when e.g a button is clicked. The best approach will probably be through Javascript. This doesn't seem complicated as I can expose functions for the javascript window.external, but the only URL my C# application sees is the /Default.aspx. All the javascript functions (window.external.myfunc(..)) has to come from this page.
Any ideas? I'm turning up blank. I'm also a bit unsure on how to call the javascript functions from code-behind. ScriptManager.RegisterClientScriptBlock seems to be used a lot, but can this be called several times at one page?
Thanks!
By the way, for the C# client I'm using WebBrowser.ObjectForScripting to a custom object which will take these window.external function calls from Javscript. This works.
The part with ObjectForScripting and window.external will work fine.
And in order to call js functions from your ASP.NET code, you should use ajax calls from the js. There are two approaches for that:
1- create a web service and invoke it constantly to check for anything that has happened (i.e polling). this is the simplest way and can be easily implemented, for example using jQuery:
$.ajax(...);
then call your window.external.func() from the callback to that ajax call (of course if it's returned the intended value). Note that with this method, you will always have a delay because the client should poll the server.
2- make a connection to the server and keep it open, then send the data from the server when it's ready. For this matter, you can make use of something like SignalR. This will solve the issue of delay, but will keep an open connection which in turn brings other issues.
Actually the main factor to decide between these two methods is whether you are okay with a delay. If it's not the problem to wait for an average of 15 seconds, use the first method with a polling time of 30 seconds. If you want it to be real-time, use the second method but be cautious with its own issue like long-running connections, lack of session-state in SignalR and so on.
I just wanted to show you the choices. please tell me if it's unclear in any manner.
Related
I know this is a general question - however I want to gain a little advice before investing a lot of time looking into something that may not be suitable.
I have a C# .NET MVP web application, it needs to complete a new complex/heavy query when a user logs in (to find new messages for a user), however needs to do so without impacting performance. I have looked into multi threading in the past, however it would still need to wait until the new query completes, and adds a lot of complexity into the solution (we do not use multi threading currently).
I am wondering if Ajax would be a solution, so once the screen loads, is it possible to kick off an ajax command after page load that would execute and refresh part of the screen with the results?
How does the application handle if the user navigates to different screen? (note I planned to add the ajax component to master/base page which is part of every screen).
Would appreciate feedback, if people think its a possible approach I would do a proof of concept to prove it out.
If it doesn't need to return result to client side you can use HostingEnvironment.QueueBackgroundWorkItem to start the task then return it to client straight away.
If the query needs to return the result to client side then you need a to use Ajax call from client to server then update the view with data returned. You may want have a look at the client side framework such as angularJS.
I am currently working on a project in ASP.NET MVC 4 and came along a module where a progress bar is needed. The question I am having right now is "What is the best way to implement an async progress bar?".
After some lookup I came across the following method:
Create a startEvent() and getProgress() in C# code.
Use javascript setTimeout() to call the getProgress() method asynchronously.
(Example: https://www.devexpress.com/Support/Center/Example/Details/E4244)
My remark with this method is that that causes the code to be dependent on the timeout you choose. So it would take some fiddling to find the best and most performant timeout.
Now the method that I would most likely have used before I researched the matter is the following:
In code behind, create a method handleItem(int index) which takes an index and does everything you want to do with the item at that index.
Determine the number of items you want to handle and pass that to your javascript.
In javascript, initiate a for loop that loops from 0 to the amount - 1, and for each index, it initiates an ajax-call to handleItem(i).
On that ajax-call's complete-statement, you can update the progress bar with the new amount.
My questions here are the following:
Does this expose too much of the program logic?
Does this create too much overhead seeing as every call goes to the server and back?
Are there any other reasons why I should refrain from using this method?
Thanks in advance
Koen Morren
This is not a recommended strategy, because the client drives the process. If there is any discontinuation of connectivity or maybe the user closes the browser, the process will stop.
Generally, if you use straight HTTP you will need to poll (aka pull) from javascript. The pseudo code is pretty much this:
Call Creates Task ID and sends it to client
Client queries the status of task with given ID
Another possibility are WebSockets, which allow your client to listen for changes that are pushed by the server.
There are many options to store the progress of a given state. You can index the progress by the HttpContext, task id, or some user id, or even store it in a database and use SqlDependency to get notifications of when the status is changed.
In summary, polling has more lag than push mechanisms. Clients should not drive an asynchronous process, but they should be either notified or provided some mechanisms on the status of an async process.
Unlike ASP.NET, there is few way to push data from server to client in MVC, WebSockets or SingnalR like api(s) can work for you.
The ajax approach is good and give you reliable mechanism to update data no matter user go to other page or closes the browser, every time ajax launched it will update UI. So there is nothing wrong there just have a fair interval in javascript.
Does this expose too much of the program logic?
Code will be written only in class file to calculate current %age.
2.Does this create too much overhead seeing as every call goes to the server and back?
No, ajax are light-weight calls
3.Are there any other reasons why I should refrain from using this method?
This method will allow user to freely navigate to other resources as ajax will work independently.
Today we have seen some sites that pass data or notification to client without page refresh. Named Real time or interactive applications.
some of known site are :
Stackoverflow : notifications
Freelancer : passes project and professional counts asynchronously in numeric format
Google Mail : Counts mail memory usage by users in total.
and so more ... .
I have tried and searched some tools like SignalR. Basically SignalR designed for creating chat application. But is there a direct way without any extension in Microsoft Technologies to meet our purpose? For example suppose we want a simple counter like freelancer, Have we no way except using extensions like SignalR?
You can look at a technique called polling (which SignalR falls back to when support for other methods are not present), basically the concept is that every x seconds you'd send a request to the server to check for an update (more or less), for example (using jQuery):
setInterval(function() {
$.get("/Messages/GetCount", function(data) {
// do something with the data ...
});
}, 30000);
Every 30 seconds, check the Messages count - and perform an action accordingly. Here is a good article on polling and long polling (it mentions a SignalR alternative called Socket.IO).
Having said all that, I'd seriously just go with SignalR, those guys tested all kinds of corner cases, performance etc.
Use a Javascript timer on the client-side to make periodic asynchronous requests for updated information. This updated information can then be used to update the client-side, or can be used to prompt further requests for more details.
This solution can work for situations where you do not need to receive immediate updates whenever there are updates available on the server side (but instead can wait for the timer interval). It also may present some scaling issues and can lead to wasting bandwidth and client/server time while making unnecessary calls.
To overcome either of these, it would be best to use a library like SignalR (which can do much more than just chat applications - check out this blog post for a real world implementation that has nothing to do with chat).
Use Microsoft's ASP.NET Ajax implementation or JQuery:
Microsoft Ajax Overview
I'm building the back end to a site which will have multiple "widgets" on the front end which need to update in real time.
Right now I simply have a load method which populates all the widgets with data, on page load obviously. My question is how to handle the real time aspect of further updates.
I thought of having just multiple ajax calls, which could query a service every second or so, and return the latest data, but that seems inefficient.
Is there a way to "push" data to a View from a Controller?
maybe you can have a look at this project : https://github.com/SignalR/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.
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.
(Excerp from http://signalr.net/ )
Hope it helps.
I think your best bet is to periodically poll the server:
$(document).ready(function() {
setTimeout("getUpdate()", 30000);
function getUpdate()
{
// Make an ajax call here
}
});
This will ask for an update every 30 seconds.
It depends on how often the data on the front end needs to be updated. Most pages aren't going to need constant updating. I don't know that there is a "best practice" threshold, but I think a good starting point would be 15-20 second updates using Ajax. Make your Ajax calls fast and lean - maybe just return blank if there are no updates. If you need faster updates than that, look into something called long polling. Long polling is basically where you trigger an ajax call to the server, and the connection sits open until there is data to be sent. Long polling will take more server resources, because you will have open connections and threads running while they are waiting for data to be ready. With ASP.NET you'll also have to worry about killing long polling threads, because by default those threads wouldn't be killed when the browser closes connection (for example if someone navigates away from the page.)
You can also use Web Sockets, if its running in a browser that support HTML5
When i enter username and password on my site. if the username and pasword are correct, then i have a c# method called on Page_Load for database (which delete the non-required records).
if there is one record or 100, i still have to wait for the page load until that process is completed :(
I am using this string to load all the files, which will be then used to compare files
HttpContext.Current.Request.PhysicalApplicationPath;
how ever if i used a static path i.e : c:/images, then things goes bad :(
so what could be the possible solultion ?
You can start the record removal asynchronously:
Asynchronous Operations (ADO.NET)
Then your Page Load will occur before the removal operation is finished.
EDIT: Since you mention that you are using an Access DB, I guess that you are not losing the time by deleting the records but by some other operation (I suspect closing the DB, see my comment to Amir's answer). The thing you should do now is to benchmark, either by using a tool (see this question) or "manually", using the Stopwatch class. Any way, before you try to optimize, use one of these methods to find out what is really causing the delay.
Use Ajax and make it async as a web service.
Edit1: What I mean is to move the code in the Page_Load into a web service method, then call that web service from javascript after the page loads, sending it the information it needs to properly perform your operation, thus the client side appears more responsive - I make the assumption that the actions taken are not required to properly render your client side code, however if not, you might consider updating the page after the web service returns. This could be done manually, through the built in ajax toolkit or via a library such as jQuery.
This doesn't sound like a async problem to me. Deleting 100 or even 1000 records in a database shouldn't take more than a few milliseconds. If I was to suspect, I would think you have not set up your indexes correctly. So instead of deleting those records using a quick index, it needs to look through every record and see if its a match.