i want when the client send to my web page request,my web page get the request and active timer and wait about 15 minute and check client so connect and response the json string.
my server code is:
string name, count;
protected void Page_Load(object sender, EventArgs e)
{
name = Request.QueryString["name"];
count = Request.QueryString["count"];
Timer1.Interval = 15000;
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (Response.IsClientConnected)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string json=jss.Serialize("در خواست شما تایید شد");
Response.Clear();
Response.Write(json);
Response.End();
}
else
{
Response.End();
}
}
how can i do this?
From your comment : " thanks,i want for example customer send my server a order and when the system manager accept the order,response to client:your order accepted"
You will need to include jQuery to do this bit.
As you have the name and count in the query string, which I take it will help you identify the customer (or change it to an order ID), then you can use the following on your .aspx page in a javascript block:
$(document).ready(function(){
setTimeout(function()
{
location.reload();
}, (15 * 60 * 1000)); // (that's 15 mins that I couldn't be bothered to work out...)
});
Your server side code could then be:
protected void Page_Load(object sender, EventArgs e)
{
var name = Request.QueryString["name"];
var count = Request.QueryString["count"];
if(OrderAccepted(name, count))
{
// display message to user
}
}
private bool OrderAccepted(string name, string count)
{
// do what you need to do to find out if the order is accepted.
}
You may also want to try and have the javascript only run if the order is not accepted so that it doesn't keep running. But a 15 min interval is a decent long period, and most people will close their browsers once they know the order is accepted.
Hope this helps.
You cannot achieve what you are trying to do through "only" server-side (compiled C#) code.
The problem is that you want the client to send a request every fifteen minutes - to get the latest JSON - but you are trying to tell the server to do that.
There are many better ways to accomplish what you are trying to do (ie, better than a fifteen-minute timer) but here is one way you can achieve that through JavaScript:
First, expose your server's API call (the call that gets the JSON).
Then, in a script node on the client (ie in a script tag in the HTML you send down), define the following function:
function refreshDataAndUpdatePage() {
$.ajax({
url: 'your/url/to/the/action',
success: function (data) {
// use data JSON to update page.
// then, call this function again recursively after a timeout of 15 minutes = 900 s = 900,000 ms
setTimeout(refreshDataAndUpdatePage, 900000);
}
}
And of course, call it somewhere.
Related
I'm sorry for potentially creating a duplicate thread here, but I simply cannot get my web application to do what I need by following the other examples I've found.
My goal is to do one of the following:
OPTION 1 - IDEAL SOLUTION
Fetch data from a database and update the UI on a web page ONLY when changes are made to the data being displayed on the web page. For example, if a user is viewing a service ticket, I don't want to update the UI on that page unless that ticket is changed.
OPTION 2 - ACCEPTABLE SOLUTION
Fetch data from a database every x seconds and use that data to update the UI on a web page.
My current implementation of Option 2 is below. It involves sending an asynchronous HTTP request every 60 seconds to fetch the data:
// start checking for new messages every 60 seconds
setInterval(function () {
$.ajax({
async: true,
type: "POST",
contentType: "application/json; charset=utf-8;",
url: "/AJAX_Handlers/CheckForNewMessages.ashx",
dataType: "json",
success: function (Result) {
var new_message_received = Result[0]["NewMessageReceived"];
if (new_message_received) {
$("#DIVMessageReminder").html("<strong>You have " + num_new_messages + " new message(s).</strong>");
$("#DIVMessageReminder").show();
}
else {
$("#DIVMessageReminder").hide();
}
}
});
}, 60000);
Rather than sending an HTTP request every 60 seconds, I would like to use SignalR to push that data to the client every 60 seconds.
As a simple example, I have created the following Hub with a method to get the current time on the server:
Imports Microsoft.AspNet.SignalR
Public Class ServerTimeHub
Inherits Hub
Public Sub GetServerTime()
Dim current_time As String = Now.ToString()
Clients.All.updateTime(current_time)
End Sub
End Class
And a basic textbox:
<input id="TXTLongPollingTest" type="text" class="form-control" />
And my client-side code:
var hub = $.connection.serverTimeHub;
hub.client.updateTime = function (new_time) {
$("#TXTLongPollingTest").val(new_time);
}
$.connection.hub.start().done(function () {
alert("connected to the SignalR hub");
hub.getServerTime();
}).fail(function (err) {
alert("failed to connect to SignalR hub: " + err);
});
At first I tried getting it to fetch the server time just once. My code will successfully connect to the hub, but then it throws an error saying "Uncaught TypeError: hub.getServerTime is not a function". That's the first problem I haven't been able to overcome.
The second problem is: How can I get the hub to send the current time to the client on a regular interval such as every 1 second?
Here is what I have done to achieve something similar. Essentially fetching data from the database and broadcasting to clients every 30 seconds.
In my global.asax.cs I have this to ensure whenever my website is has started/restarted it will kick off my repeater:
protected void Application_Start(object sender, EventArgs e)
{
GetTeamData.TeamDataRepeater();
}
In my GetTeamData.cs I have a timer that is set to run every 30 seconds
public class GetTeamData
{
static Timer TeamDataTimer = new Timer();
public static void TeamDataRepeater()
{
TeamDataTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent_TeamDataBroadcaster);
TeamDataTimer.Interval = 30000; //30 Seconds
TeamDataTimer.Start();
}
public static void OnTimedEvent_TeamDataBroadcaster(Object sender, ElapsedEventArgs e)
{
updateFirstRow();
}
public static void updateFirstRow()
{
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MsgHub>();
hubContext.Clients.All.pushMyData(mydata1, mydata2, mydata3);
}
}
My java script for the client has:
//I have already started my connection
$(function () {
var chat = $.connection.msgHub;
chat.client.pushMyData = function (mydata1, mydata2, mydata3)
{
//Do something with the returned data now
}
});
Note that I have removed some things such as use of try/catch just to give you an example.
Hope that helps.
I want to redirect a post from /mynode to /eng/mynode/ and preserve form data.
I've tried "Server.Transfer" but I get an error saying "Error executing child request for /en/mynode".
I would like to implement this in a general fashion, for example in OnPreInit() method of base page.
Do you see any other options?
P.S. When you use Server.Transfer, "the page transferred to should be another .aspx page. For instance, a transfer to an .asp or .asmx page is not valid". See source.
I suppose you can write something like:
protected void Page_Load(object sender, EventArgs e) {
Response.Clear();
Response.Write(#"<html>");
Response.Write(#"<body>");
Response.Write(#"<form id=""form"" action=""/eng/mynode/"" method=""post"" enctype=""application/x-www-form-urlencoded"">");
for(int i = 0; i < Request.Form.Count; i++) {
var key = Request.Form.GetKey(i);
var values = Request.Form.GetValues(i);
foreach(var value in values) {
Response.Write(string.Format(#"<input type=""hidden"" name=""{0}"" value=""{1}"" />", key, Server.HtmlEncode(value)));
}
}
Response.Write(#"</form>");
Response.Write(#"<script>document.getElementById(""form"").submit();</script>");
Response.Write(#"</body>");
Response.Write(#"</html>");
}
Once the user logs in, i am displaying an alert to user based on a check on page load method. Now when the user navigates to other aspx pages and clicks on home again, I don’t want him to see the alert again. I want to achieve this with jquery and session variable. In a way I want to check first page load by jquery using a session variable.
I could do this with Session and RegisterStartupScript
User Login code
public void doLogin(string userName, string pwd)
{
// validate user
// check to see whether need to show alert
Session["ShowAlert"]=true;
Response.Redirect("Home.aspx");
}
in Home.aspx
Option 1
protected void Page_Load(object sender, EventArgs e)
{
if(Session["ShowAlert"]!=null)
{
String scriptName = "PopupScript";
if (!IsClientScriptBlockRegistered(csname1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\"> function showUserAlert() {");
cstext.Append("alert('message');} ");
cstext.Append("</script>");
RegisterStartupScript(cstext, cstext.ToString());
Session.Remove("ShowAlert");
}
}
}
Option 2:
Just define a javascript variable var in the page and use it in $(function(){...})
protected void Page_Load(object sender, EventArgs e)
{
if(Session["ShowAlert"]!=null)
{
String scriptName = "PopupScript";
if (!IsClientScriptBlockRegistered(csname1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\">");
cstext.Append("var showAlert=true;");
cstext.Append("</script>");
RegisterClientScriptBlock(cstext, cstext.ToString());
Session.Remove("ShowAlert");
}
}
}
JS
$(document).ready(function(){
if(showAlert)
{
alert('ShowMessage');
}
});
I made this exact feature a couple of weeks ago, but used a mySQL database instead of using sessions. If you are wanting to display the alert to the user only once EVER (or as close to forever as possible) or just once a week etc, then you should use cookies instead of sessions.
Otherwise, you can detect when the page has loaded simply with jQuery:
$().ready(function(){
if(!$.session.get("viewed_page")){
alert("some message");
$.session.set("viewed_page", true);
}
});
No need for session here.
You can use the session cookie itself.
$(function (){
if (document.cookie.indexOf("yourToken")>-1)
{}
else
{
// show the window , and set a cookie
}
});
I am newbie with asp.net. I have a url of video http://localhost/video/file.mp4 , but i want to serve url like http://localhost/34567fghft/file.mp4 to make timeout for url, is there some solution to my question? Sr for my english, im stuct around with this, waiting for your answers, thanks
You can on Global.asax, and on Application_BeginRequest to get the requested path, split it, see if has expired or not, manipulate the string and send him ether to an error page, ether rewrite it to the real path:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if (cTheFile.EndsWith("/file.mp4", StringComparison.InvariantCultureIgnoreCase))
{
// manipulate your string to see if is expired...
string[] keys = HttpContext.Current.Request.Path.Split('/');
// get the 34567fghft part
if (IfExpired(keys[keys.Length - 1]))
{
HttpContext.Current.Response.Redirect("ExpiredMessage.aspx", true);
return ;
}
else
{
HttpContext.Current.RewritePath("http://localhost/video/file.mp4", false);
}
}
}
Please note this code is the idea on how you do it. Is need some better string manipulation and error check.
I'm currently stuck. I have a webform with a button that registers or saves a record.
What i'd like to is have it display a javascript alert and then redirect to a page.
Here is the code i am using
protected void Save(..)
{
// Do save stuff
DisplayAlert("The changes were saved Successfully");
Response.Redirect("Default.aspx");
}
This code just redirects without giving the prompt Saved Successfully.
Here is my DisplayAlert Code
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');", message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true
);
}
Can anyone help me find a solution to this?
Thanks
You can't do a Response.Redirect because your javascript alert will never get displayed. Better to have your javascript code actually do a windows.location.href='default.aspx' to do the redirection after the alert is displayed. Something like this:
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');window.location.href = 'default.aspx'",
message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true);
}
The DisplayAlert method adds the client script to the currently executing page request. When you call Response.Redirect, ASP.NET issues a HTTP 301 redirect to the browser, therefore starting a new page request where the registered client script no longer exists.
Since your code is executing on the server-side, there is no way to display the alert client-side and perform the redirect.
Also, displaying a JavaScript alert box can be confusing to a user's mental workflow, an inline message would be much more preferable. Perhaps you could add the message to the Session and display this on the Default.aspx page request.
protected void Save(..)
{
// Do save stuff
Session["StatusMessage"] = "The changes were saved Successfully";
Response.Redirect("Default.aspx");
}
Then in Default.aspx.cs code behind (or a common base page class so this can happen on any page, or even the master page):
protected void Page_Load(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty((string)Session["StatusMessage"]))
{
string message = (string)Session["StatusMessage"];
// Clear the session variable
Session["StatusMessage"] = null;
// Enable some control to display the message (control is likely on the master page)
Label messageLabel = (Label)FindControl("MessageLabel");
messageLabel.Visible = true;
messageLabel.Text = message;
}
}
The code isn't tested but should point you in the right direction
This works perfect:
string url = "home.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Saved Sucessfully.');window.location.href = '" + url + "';",true);
protected void Save(..)
{
// Do save stuff
ShowMessageBox();
}
private void ShowMessageBox()
{
string sJavaScript = "<script language=javascript>\n";
sJavaScript += "var agree;\n";
sJavaScript += "agree = confirm('Do you want to continue?.');\n";
sJavaScript += "if(agree)\n";
sJavaScript += "window.location = \"http://google.com\";\n";
sJavaScript += "</script>";
Response.Write(sJavaScript);
}