How can I get the current time as Universal time in classic asp. I know how to get in C# and I am getting the universal time in c# with following line ((DateTime.Now).ToUniversalTime()).ToString("s") and this code gives me time like this 2012-07-09T10:29:49
But I want to know the equivalent in classic asp. Thanks
As Ian pointed out you can generate a UTC time via Javascript.
You specified "ASP Classic" which of course includes Javascript as a language (Actually JScript, based on ECMAScript v3), so there's one answer for you: Call (new Date()).toUTCString().
If by chance you prefer to code your pages in mostly VBScript, you can mix in just a little JScript to get it done. You don't need to resort to Server.Execute or Sessions to make that happen.
This works for me:
<%# language="VBScript" %>
<script language='JScript' runat='server'>
function jsGetUTCTime() {
var d = new Date();
return d.toUTCString();
}
</script>
<script language='VBScript' runat='server'>
Function getUTCTime()
' Use JScript to get the current GMT time stamp
getUTCTime = jsGetUTCTime()
End Function
</script>
<!DOCTYPE html>
<html>
<head>
<title>Mix</title>
</head>
<body>
<h2>The time is:</h2>
<%= getUTCTime() %>
</body>
</html>
According to u229.no, there isn't any built-in way in VBScript to convert to UTC.
Take a look at the code the author provided below which uses JScript, and how you can call this from VBScript.
The GetServerGMT routine will return something like: Wed, 01 Feb 2006 15:21:59 UTC.
Function GetServerGMT()
// Use JScript to get the current GMT time stamp and store it in Session("ServerGMT")
Server.Execute "GetServerGMT.asp"
GetServerGMT = Session("ServerGMT")
End Function
And this is how the GetServerGMT.asp file with the jscript code looks like:
<%#language="jscript"%>
<%
var od = new Date();
var nd = od.toUTCString();
Session("ServerGMT") = nd;
%>
There are other jscript methods that you can use as well.
An alternative approach is
%>
<script runat="server" language="javascript">
function getTimezoneOffset() {
return (new Date()).getTimezoneOffset()
}
</script>
<%
Function nowUtc()
nowUtc=DateAdd("n",getTimezoneOffset(),Now)
End Function
Variation on above code
<%# language="VBScript" %>
<!DOCTYPE html>
<html>
<head>
<script language='Javascript' runat='server'>
// good for creating cookie timestamps that match RFC 1123
function jsGetFutureTimeGMT(minutes) {
var d = new Date();
var future = new Date();
future.setTime(d.getTime() + (minutes*60000));
var utcString = future.toUTCString();
var tz = utcString.indexOf("UTC");
if (tz > 0) {
utcString = utcString.substring(0, tz) + "GMT";
}
return utcString;
}
</script>
<title>ASP Classic RFC 1123 compliant GMT timestamp</title>
</head>
<body>
<h2>ASP Classic RFC 1123 compliant GMT timestamp</h2>
<pre>
The VBS time right now is: <%= Now() %>
The time in 10 minutes is: <%= jsGetFutureTimeGMT(10) %>
</pre>
</body>
</html>
If your application is connected to a database, you can probably get a timestamp from the database with a simple fast query. For example, in MySQL it's: SELECT unix_timestamp().
This will give you a Unix Timestamp (seconds since the Unix Epoch). From there convert into whatever format you like.
Related
The following code:
<%
Response.Write("VB comes second!")
'page1()
Dim p
Set p = New Page
%>
<script language = "Python" runat="server">
Response.Write("Python comes first!")
class Page:
def display_top(self):
Response.Write("""
<html>
""")
def display_body(self, body_text):
Response.Write("<body>"+body_text+"</body>")
def display_bottom(self):
Response.Write("""
</html>
""")
def page1():
p = Page()
p.display_top()
p.display_body("This is my body!")
p.display_bottom()
</script>
Gives the error:
Error Type:
Microsoft VBScript runtime (0x800A01FA)
Class not defined: 'Page'
/website/index.asp, line 6
But why?
If I call the function page1() from within the VBScript, then it works as expected.
Thanks,
Barry
EDIT 1:
This:
<script language = "Python" runat="server">
class Page:
def display_top(self):
Response.Write("<html>")
</script>
<%
Dim p
Set p = server.createobject("Page")
%>
Gives the error:
Invalid class string
If I use:
Set p = New Page
instead, then I get:
Class not defined: 'Page'
I can't find a definitive source for this, but I'm pretty sure that the VBScript New keyword can only be used to instantiate classes defined in VBScript using the Class keyword. What you should do instead is write a "factory" function in Python that will return a new Page object. Then you can call that function from VBScript.
I don't know Python, but here's an example with VBScript and JScript to illustrate the point:
<%
Dim p
Set p = makePage("hello")
Response.Write p.foo
%>
<script language="JScript" runat="server">
function Page(foo) {
this.foo = foo;
}
function makePage(foo) {
return new Page(foo);
}
</script>
You are hitting a asp engine limitation right there.
Code in <script runat=server> blocks may run at different times.
Server Script Order of Execution
Inline server script runs sequentially, top to bottom. You can define callable routines (functions or subroutines) in server script, and they will be called as needed.
All inline script has to be in the same language namely, the language specified in the # directive at the top of the page. Therefore, you can't mix scripting languages in inline script.
"But wait!" you might say. It is theoretically possible to put inline-like script into a <SCRIPT> element that is, have script in the element that is not part of a function or subroutine, as in the following example:
<% Response.Write("Some inline script<BR>")%>
<SCRIPT LANGUAGE="VBScript" RUNAT="Server">
Response.Write("Script in a SCRIPT element<BR>")
</SCRIPT>
Yes, you can do this. *However, you are then at the mercy of the order of execution of the IIS ASP processor.*
Ordering Script Blocks
When you are mixing languages, the order in which <SCRIPT> blocks appear in the page can make a difference as to whether they work properly. Consider this simple case of an inline VBScript script calling a function written in JScript:
<SCRIPT LANGUAGE="VBScript">
' Calls a JScript function
aNumber = 2
doubledNumber = doubleMe(aNumber)
document.write("The answer is " & doubledNumber)
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
function doubleMe(aNumber){
return aNumber * 2;
}
</SCRIPT>
This won't work. More specifically, the document.write statement will write an empty string to the page. Why? Because at the time the VBScript block is being processed, the following JScript <SCRIPT> block has not yet been read, parsed, and made available to the page. When the browser processes the script blocks in the page, it works from top to bottom.
In this case, simply reversing the order of the script blocks solves the problem. And in fact, this type of scenario is not all that common—for the most part, <SCRIPT> blocks contain functions and subroutines that will not be called until the page has been fully loaded and all elements are available. Nonetheless, you should keep in the back of your mind the fact that pages are processed linearly and that <SCRIPT> blocks in different languages are processed separately.
To learn more, pls visit this MSDN knowledge base article.
Proof that the class defined in one script block is reachable from another script block;
<%
Response.Write "VBScript Here - 1 <p>"
hello()
apple.color = "reddish"
response.write (apple.getInfo())
%>
<script language=JavaScript runat=Server>
Response.Write("Javascript here - 2 <p>");
function hello()
{
Response.Write("Hello from JS <p>");
}
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple' + '<p>';
}
}
</script>
<%
Response.Write("VBScript here - 3 <p>")
%>
<script language=JavaScript runat=Server>
Response.Write("Javascript here - 4 <p>");
</script>
<%
Response.Write("VBScript here - 5 <p>")
%>
will give you this
Javascript here - 2
Javascript here - 4
VBScript Here - 1
Hello from JS
reddish macintosh apple
VBScript here - 3
VBScript here - 5
You need to reverse the script order. When your script encounters a function call, it allows that function block to be in any code block on the page within the same scope. This is not true when instantiating objects. While instantiating objects, the object code must be processed before the instantiating line. Scripting is for all intents and purposes executed linearly.
The problem is the order of execution. I don't have python installed on my server. So I did a test for you with JS vs VB - which is the same problem I referred to. Take a look;
<%
Response.Write "VBScript Here - 1 <p>"
%>
<script language=JavaScript runat=Server>
Response.Write("Javascript here - 2 <p>");
</script>
<%
Response.Write("VBScript here - 3 <p>")
%>
<script language=JavaScript runat=Server>
Response.Write("Javascript here - 4 <p>");
</script>
<%
Response.Write("VBScript here - 5 <p>")
%>
will give you this
Javascript here - 2
Javascript here - 4
VBScript Here - 1
VBScript here - 3
VBScript here - 5
Hello all i have the following code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest()
}
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readystate == 4 && xmlhttp.status == 200)
{
document.getElementById('hint').innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","sample.aspx?q=" + str ,true)
xmlhttp.send()
}
</script>
</head>
<body>
Type here: <input type="text" id="txt" onKeyUp = "showHint(this.value)"/>
Suggestion here: <div id="hint"></div>
</body>
</html>
but this example not working..it is saying access is denied (script error)
How to solve this..!
My aspx page follows like this
<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if
'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>
You have two separate issues. First, your sample.aspx should be sample.asp, as it is a classic asp page, not a .Net asp page. Make sure you change the path in the xmlhttp.open method as well.
Second, xmlhttp.readystate should be xmlhttp.readyState - note the capital S. Took me a bit to figure that part out.
The problem might be that you're running the HTML file in file:// protocol. As far as I'm aware, server files like .php & .asp don't work in file:// protocol.
If you really want this to work, try setting up Apache and put your files inside your server folder. If you're in Linux, it's in /var/www, with other operating systems I'm not so sure.
Also, thought it's unrelated, I would recommend changing your Doctype to <!DOCTYPE html> as it is the standard now. Sorry. You don't have to.
Best of luck!
How do I register a Javascript variable on the server side (backend) and access it on the client side (Javascript file), without a hidden field, Literal, etc.?
You can use the RegisterClientScriptBlock-Function from the Page's ClientScriptManager.
Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "initMyClientVariable", "var myClientVariable=null;", True)
EDIT: according to your new informations, that you want to register a client array, use ClientScriptManager's RegisterArrayDeclaration Method.
VB.Net example:
Dim myArrayValue As String = """1"", ""2"", ""text"""
Page.ClientScript.RegisterArrayDeclaration("myClientArray", myArrayValue)
According to the new information in my comments that you need access to that variable from an external js-file: you should pass the js-array as argument to the function in the js-file. For example:
callFunctionInJsFile(checkBoxes);
You can put the following code in .aspx file ...
<script type="text/javascript" >
var date1 = "<%: DateTime.Now %>";
var date2 = "<%= DateTime.Now %>";
</script>
<%: %> works under ASP.NET 4
You can put a literal in the xml portion of the code and assign that literal some text:
myLiteral.Text = "<script language=\"javascript\">var myVar = 24;</script>";
This makes myVar globally available on the client side once it's rendered. You can also use the ClientScriptManager object to use Asp.Net to inject scripts and variables.
First place an <asp:Literal ID="Literal1" runat="server"></asp:Literal> tag in the <head> of your .aspx file. Then in the server side code in your .aspx.cs file, do something like Literal1.Text = "<script type=\"text/javascript\">var timer = 3600</script>" and you've got yout javascript variable called timer.
That's it. Have fun!
I am very new to jQuery and have got a quick question.
I wish to use my server side classes in my jQuery code, something similar to this:
$(document).ready(function() {
var temp = <%# myClass.Id %>;
})
Is this possible? if so, how?
Thank you very much
This is the later question I refined my former question to:
I'm sorry, I think I didn't explain myself too well... I've got a class name User. It's a class I built in my business logic.
I've got a web page named UserProfile, inside it I've got the following property exposing the current logged in user:
public BL.User CurrUser { get { return (BL.User)Session["currUser"]; } }I want to be able to access this User class from my aspx page using Jquery. How do I do that?
The databinding syntax
<%# MyStaticClass.MyProperty %>
will only work if you call DataBind on the container (page). What you're after is most likely the following syntax:
<%= MyStaticClass.MyProperty %>
which will also give you access to you page / control members
<%= this.MyPageProperty %>
As was already mentioned you should really assign those values to java script variables and pass those variables to you JS functions.
This will only work if your javascript is embedded in your source files (e.g. the .aspx files):
<script type="text/javascript">
var id = <%# myClass.Id %>; // store as raw value
var id_string = '<%# myClass.Id %>'; // store in a string
</script>
As others have said, if the JavaScript is in your aspx page, then using server tags will work fine.
If you have your jQuery in an external script file, then you could put this in your aspx page
<script type="text/javascript">
var myClass = $('#<%= myClass.ClientID %>');
</script>
and then use the variable in your external script file
$(function() {
myClass.click( function() { ... });
});
For other options take a look at this question and answer - How to stop ASP.NET from changing ids in order to use jQuery
I need to set a single property in a jQuery command using a value that is calculated in the code-behind. My initial thought was to just use <%= %> to access it like this:
.aspx
<script type="text/javascript" language="javascript">
$('.sparklines').sparkline('html', {
fillColor: 'transparent',
normalRangeMin: '0',
normalRangeMax: <%= NormalRangeMax() %>
});
</script>
.aspx.cs
protected string NormalRangeMax() {
// Calculate the value.
}
It smells odd to have to call from the ASPX page to just get a single value though. Not to mention I have an entire method that does a small calculation just to populate a single property.
One alternative would be to create the entire <script> block in the code-behind using clientScriptManager.RegisterClientScriptBlock. But I really don't like putting entire chunks of JavaScript in the code-behind since its, well, JavaScript.
Maybe if I end up having many of these methods I can just put then in a partial class so at least they are physically separate from the rest of the code.
What method would you recommend as being easy to understand and easy to maintain?
The <% %> works fine. One thing that I do is set a value in a hidden field on the page (then writing the necessary javascript to extract that value), this is nice because I can change that hidden field via javascript and when/if the page posts back I can get that new value from code behind as well.
If you need to call the method on demand, you could do an jQuery AJAX call to a ASP.NET WebMethod to grab the data and re-populate the various options. You can find a good tutorial on how to do that here: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Below is some sample code using the hidden field method (using the datepicker control, but you'll get the idea):
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtCalendar" runat="server" />
<asp:HiddenField ID="hfTest" runat="server" />
</div>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ui.jquery.com/latest/ui/ui.datepicker.js"></script>
<script type="text/javascript">
var dateMinimum = new Date($("#<%= hfTest.ClientID %>").val());
$(function() {
$("#<%= txtCalendar.ClientID %>")
.datepicker({
minDate: dateMinimum
});
});
</script>
</body>
And the code behind Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
// Set Value of Hidden Field to the first day of the current month.
this.hfTest.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToString("MM/dd/yyyy");
}
Personally, I would use the <% %> method. This is what the view is for. I don't like the RegisterClientScriptBlock at all. If you ever move to MVC you will get used to the <% %> ... :)
I ran into this problem a while back. I recommend <% %> for single variable stuff. I find the RegisterClientScriptBlock function useful only if I ever need the code-behind to determine which scripts to run.
Rick has a nice article about passing server vars to client script