Refresh asp.net page from a code-behind file - c#

I have an ASP.NET website and a seperate C# application. The application writes data to a file, the website populates the treeview with the data in the file. I populate the treeview in the page Load event.
The website checks if the file has changed. This happens from a code behind file. If the file did change, the website needs to be refreshed. I cannot use Response.Redirect because I get a
Response is not available in this context
I tried System.Web.HttpContext.Current.Response.Redirect, but this gives me a NullReference.
How can I refresh the page from a code behind file, so that it loads the right data in the treeview? Other suggestions that work but use something else than refreshing the page are welcome. Thanks in advance!
Edit: The actual problem is dynamically updating the treeview (new data = updated treeview). I have tried to do something with data from a MySql database but failed. The idea is the same, except the data isn't coming from a file but from a database. I added this because I thought this info might help users understand my problem.

you can't send data to the client from an initiative of the server.
You will have to poll (jQuery/ajax) if new data is available, then refresh from the client side.
this involves basically :
on the server
a web service, webmethod page method, custom handler, etc. that can tell if new data is available
on the client
a timer that query the server if data is refreshed, and, in this case, that refresh the page, or reconstruct the DOM if using some JS templating
[Edit] a bit of background :
Actually, System.Web.HttpContext.Current.Response is null because of the asynchronous model of the Http protocol. The browser emits a request "http://srv/resource", the server intercept it on the port 80 (by default), parse the request, build a response (mostlya bunch of html content) and send the response the browser. Then the connection is closed. This choice allows a great scalability, as it does not requires to keeps thousands of connections alive with nearly no data passing on it.
The impact of this, is that the web server have to knowledge of the client, other than what is send in the request. The server receive text, and send text in return.
Microsoft has created the ASP.Net framework to reproduce the RAD feeling of desktop applications. You think with controls and events, not in producing html flow like ASP or PHP. They succeeded in the sense, that, building web apps are quite similar to desktop development.
The quite is actually what is causing you some confusion. Even if the asp.net framework encapsulate most of the plumbing (viewstate is the key) to simulate this behavior, asp.net will, at least, still be a parser for request text that produces a html text to send to the client, in one shot.
So you have to cheat. You can, as I suggested, automate the browser (using javascript) to wrap this asynchronous work into a "dynamic" application.

You can't successfully use a FileSystemWatcher from within a webpage.
The instance of the page lives just long enough to handle a single request. And after that request has been served, you can't issue a redirect. The browser will not be listening anymore.
You need to do polling from your webpage, using the date you last read that file. If the Last Modified date of that file has changed from what you remember, you will need to refresh your page.

Related

What is the best practice to handle long external process in ASP.NET page?

An example will be something like: User clicks a button on a webpage I created with ASP.NET.
My app calls an API hosted on a third party server. The user sees a spinning icon/Please wait message, while my app is waiting the third party server to return the results to me, which may take a minute.
The solution isn't limited to what version of .NET.
In most cases, since you can't wait for code behind to finish (since the web page is stuck up on the server), and ONLY after ALL your code behind is done, can the page THEN travel back down to client side, be re-freshed, JavaScript starts running, and THEN the results are displayed client side. In effect code behind NEVER interacts directly with the user, but only with the web page and ONLY while the page has been posted up to the server, travels up to the server. Your code behind can then in this very short time, modify values on the page, and then the while page is sent back to the client.
So, what this means is you have to adopt ajax. That means you write JavaScript client side, and they can call a web service you setup on your web site. In such cases then, no post-back of the page has occurred, and there are "many" features of JavaScript that allow you to do this. (such as promise, await, etc.). So, most web service calls by nature are asynchronous (you don't know how long you have to wait). So, yes, this is quite much the best practice, and how this common type of issue is to be approached.
So, in effect you not use code behind on the web page for this, but create a web service (web method) for the given page, or a separate aspx page with your required web service calls. Such pages do NOT have use of the controls on your current page, don't have use of ViewState, but can use session().
So, just google making web service calls in asp.net.
You can however also start a new process thread, and have it talk to that "other service". And then say drop in a timer (and even a up-date panel ). It could trigger every one second, and poll say a database (or session()) values to determine when done, and then update the web page, and then stop the timer.
So, the timer trick means you can often avoid writing a web service, and then having to wire up the ajax calls to web methods in JavaScript. (this is the correct way, but the timer + starting another process can work quite well also, and in most cases eliminates the need for a web service and ajax calls).

Masking 1000 ajax post request with better performance

We have an application that is installed on some 600 odd servers. This application exposes a web api which gets me version information of the application.
My requirement is to display the version of application on each of the server. I have achieved this in asp.net application by:
Writing a web method in aspx.cs page with server name as parameter. This method will build web api URL, invoke web api, get response, build a object and return as json string.
I have written an jquery ajax post request for each server name to the above method. On success, built a html table row and append it to table. so that as and when we get response it is shown to user.
This works absolutely fine for say 30-40 servers. But when it increases, it takes lot of time to process all requests (30 - 40 mins). And with multiple users using this asp.net app, we start getting error.
Is there a any other method to achieve this faster and for multiple users without errors?
How often is this information changed? If this data is rarely updated, I suggest the following.
Make every of servers to save this information into a shared database table when the server starts. If the application version can be changed while the server is operating, update a corresponding record in a database.
When your service gets information about the application version, get it once from the database table instead of requesting it directly from every server.

Render view and download file in the same request

When a user has completed a form the user is redirected to the thank you page. The thank you page shall render it's view, but also download a file (pdf / a stream).
I would prefer to do this without using javascript like this
return both a file and a rendered view in an MVC3 Controller action and I would prefer to get the Save As dialog.
Has MVC any conventions that can handle this?
As #BenRobinson pointed out, you can't return two responses from a single request. No, MVC doesn't have any conventions to handle this because it's a fundamental limitation of the platform you're developing on, the Internet, and specifically the TCP/IP and HTTP protocols.
Fundamentally, the web revolves around what's called the request-response cycle. A client (usually a web browser) issues a request to a server, and that server responds with the requested resource. What you're talking about would be akin to request-response-response, which is not possible. The server cannot just up and send a response to a client without first receiving a request.
As a result, your options are:
Use JavaScript to programmatically issue another request, such as by setting location.href as the accepted answer on your linked question suggests.
Provide a link/button/whatever to allow the user to initiate a request for the file manually.
That's it. Either way, you need a new request, either initiated by JavaScript or the end user to get the file.
Did you tried meta refresh Trick.
<META HTTP-EQUIV='REFRESH' CONTENT='5;URL=http://www.example.com/test.txt'>
Remember to set the header Content-Disposition: attachment for the file that you want to download in browser.

Service to ASP.NET Communication

A little background... I have a .NET webpage that communicates one way with a service. (using OnCustomCommand()) When the user presses a button, a function is called. Which is all good and dandy, however when the function is done executing I need to be able to send a message, function call, or some communication to the .NET webpage.
Is there a way for my service to call a function, send message or update my .Net webpage?
I've looked around and seen mostly .NET -> Service but nothing seems to go the other way.
EDIT: Its a windows service, and the ASP page and WindowsService reside on the same server.
Have the service write the output to a common area... such as a shared file, or a database. Then refresh the webpage and have it query that file for the response output.
Support more than one user you should have have some session ID that will be used to determine where the output is saved. For example, call a command line parameter with a GUID like this:
Echo This is a test > c:\Some Directory\Session12345.txt
And then have your aspx page query and refresh using a GET like this http://example.com/GetOutput.aspx?Session=12345
From there use ASP to access a file with an appended SessionID in the URL.
You can extend this concept to work with JQuery and WCF as needed. Of course, you will need to add security to this to prevent MITM attacks. But it sounds like this is a small project not connected to the internet so the extra features may not be that important.
Communication can only be done from client to server. Use Ajax/webservice/scriptmethod for retrieving status of service call.

Send HTTP Post with default browser with C#

I am wondering if it is possible to send POST data with the default browser of a computer in C#.
Here is the situation. My client would like the ability to have their C# application open their browser and send client information to a webform. This webform would be behind a login screen. The assumption from the application side is that once the client data is sent to the login screen, the login screen would pass that information onto the webform to prepopulate it. This would be done over HTTPS and the client would like this to be done with a POST and not a GET as client information would be sent as plain text.
I have found some wonderful solutions that do POSTS and handle the requests. As an example
http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx
So the TL;DR version of this would be
1) Open Browser
2) Open some URL with POST data
Thanks for your help,
Paul
I've handled a similar situation once by generating an HTML page on the fly with a form setup with hidden values for everything. There was a bit of Javascript on the page so that when it loaded, it would submit the form, therefore posting the data as necessary.
I suspect this method would work for you.
Generate a dictionary of fields and values
Generate an HTML page with the Javascript to automatically submit when page is loaded
Write page to a temp location on disk
Launch default browser with that page
Remember though that POST data is sent plaintext as well. POST is generally the way to go for more than a couple fields, as you can fit in more data (2048 byte limit on URLs) and that your user has a friendly URL to see in their browser.
Nothing is sent as plain text when you use SSL, it is encrypted. Unless you set what the default browser is (IE, Firefox, Chrome, etc), then you'll have to figure out what the default browser is and use its API to do this work (if it's possible).
What would probably be must faster and more efficient would be to open the default browser by invoking a URL with Start Process and pass the information on the query string (this is doing a GET instead of a POST, which I know isn't what you're asking for).
The response from the server could be a redirect, and the redirect could send down the filled-out form (storing the values in session or something similar).
That way the complexity is pushed to the website and not the windows application, which should be easier to update if something goes wrong.
HTH
Can you compile your logic in C# and then call it from PowerShell? From PowerShell you can very easily automate Internet Explorer. This is IE only but you might be able to also use WaitnN.
Anything you put at the end of the URL counts as the querystring, which is what GET fills. It is more visible than the POSTed data in the body, but no more secure with regard to a sniffer.
So, in short, no.

Categories