Im struggling to get a web method to work in VB. The javascript gets called but never seems to call the web method. I am running in debug mode and get no errors.
Here is the code:
<System.Web.Services.WebMethod()>
Public Shared Sub PasteEvent(EventID As Integer,
startDate As DateTime,
endDate as DateTime,
newStart As DateTime)
' work out the diff between start and end
Dim difference As long = DateDiff(DateInterval.Minute,startDate,endDate)
' pasteStart + minutes from the event start
' this is because we can only paste on the hour, but events may have started after the hour
' ie 10:15
newStart.AddMinutes(startDate.Minute)
' new end = pastestart + diff
Dim newEnd As DateTime = newStart.AddMinutes(convert.ToDouble(difference))
' call database
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Blueprint").ToString())
Dim cmd As New SqlCommand
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spOPSCopyEvent"
cmd.Parameters.AddWithValue("#EventID", EventID)
cmd.Parameters.AddWithValue("#StartDate", newStart)
cmd.Parameters.AddWithValue("#EndDate", newEnd)
cmd.Connection = conn
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End sub
The javascript that calls it:
<script type="text/javascript" language="javascript">
function eventCopy(eventID, start, end)
{
alert("copy");
// grab the event id and store it in a hidden text box
$("#ctl00_MainContent_hidCopyEventID").val(eventID);
$("#ctl00_MainContent_hidCopyStart").val(start);
$("#ctl00_MainContent_hidCopyEnd").val(end);
}
function eventPaste(eventStart)
{
alert("paste");
alert(eventStart);
// Call a web method, passing the eventID and the new start time
var eventID = $("#ctl00_MainContent_hidCopyEventID").val;
var startDate = $("#ctl00_MainContent_hidCopyStart").val;
var endDate = $("#ctl00_MainContent_hidCopyEnd").val;
PageMethods.PasteEvent(eventID, startDate, endDate, eventstart)
}
</script>
So far I have :
Updated my script manager in the master page to have enablePageMethods="true"
Tried adding Imports System.Web.Services
Moved the javascript into the body rather than the head
The problem is that you are missing exception handling mechanism to
see what error did you get .
Put try and catch in javascript and vb code and print the error.
Use the sniffer like Fidler to see what you are sending .
Try to print trace messages in web services using
Trace.Log and you can see them after running DebugView and see where you are falling
When using this line:
var eventID = $("#ctl00_MainContent_hidCopyEventID").val;
I should have put:
var eventID = $("#ctl00_MainContent_hidCopyEventID").val();
Accepting Gregorys answer as fiddler was the most helpfull in diagnosing the issue.
Related
I am invoking java classes on a Javascript engine, so I am limited on what I can do.
The code works fine, but when I invoke the Javascript on a loop, it times out after the first invocation.
The code just downloads a ZIP from a url, and stores it to a path. Here is the full code:
var result = (function() {
var URL = Packages.java.net.URL;
var Files = Packages.java.nio.file.Files;
var Paths = Packages.java.nio.file.Paths;
var StandardCopyOption = Packages.java.nio.file.StandardCopyOption;
var urlAddr = new URL(
target_url
);
var connection = urlAddr.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", bearer);
connection.setReadTimeout(20*1000);
connection.connect();
Files.copy(connection.getInputStream(), Paths.get(file_path+new_filename+".zip"), StandardCopyOption.REPLACE_EXISTING);
return "";
}());
The error I am getting from the server:
Java Exception: java.lang.RuntimeException: java.net.SocketTimeoutException: Read timed out: during call of javax.script.ScriptEngine.eval.
Before someone suggests, I cant get away from the java being called inside the javascript.
I thought it could be a connection being kept open.
UPDATE: this javascript for some reason is always taking 5 minutes to run....
UPDATE2: Files.copy seems to be the issue, since its the one taking the 5 minutes from the code.... the file is very small, and 5 min wouldnt justify
My search query not working when i get variable data from javascript here is code .It is not showing me any record. When i use break point i get (GetScreenshot value="") it not give the that value which he contain when i run the page.actually it has value.any help
<asp:Label ID="GetScreenshot" runat="server" ></asp:Label>
<script>
$(document).ready(function () {
document.getElementById("GetScreenshot").innerText = localStorage.getItem("Value");
});
</script>
**The asp.net code is**
private int BindList(int PageNo)
{
int TotalRows = 0;
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SELECT Image FROM [ezitaske_db].[tasker_usr].
[Screenshot] where Task='"+GetScreenshot.Text+"'");
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
//TotalRows = Convert.ToInt32(cmd.Parameters["#TotalRows"].Value);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
return TotalRows;
}
If I understand the code you've provided:
Your JavaScript code is executed when the page loads. BindList is executed when you've received a request, when you're preparing the response. As a result, there's no value in the GetScreenShot control for your BindList method to work with, because $.document.ready() hasn't executed.
The problem here is understanding the order of events for rendering a page in ASP.NET. You should be able to google this content for the specific technology you're using (ASP.NET classic, core, MVC, etc.), as changes have been made over the years.
It's particularly important to note that JavaScript code only executes after the HTML, CSS, and JavaScript has reached the browser, and at that point no .NET code can interact with your JavaScript document until a postback occurs or a request is made.
I'm to .NET and all the associated cool stuff you can do, but am wondering about efficiency with User Controls and JS includes.
My user controls are mainly made up with an ascx display page and .vb.ascx code behind, as is customary with the code-behind coding style of .NET, which is great for coding simplicity although it does double then bear of files required. However, as I understand it, the server compiles these and returns the HTML efficiently.
Where the Control requires JavaScript, as I'm developing, I am making external JS files for each User Control with the same name, so the user controls consist of 'controlName.ascx, controlName.vb.ascx, controlName.js'
If a page requested by the user contains several User Controls the browser will be requesting multiple JS files, probably a master page JS file, jQuery AND each required file for the respective Controls.
This approach makes sense to me whilst developing and as everything's all kept nice and neat, making problem solving easy, but when it goes live there'll be loads of get requests from the browser, given that each time the browser gets a file, even the process of requesting the file to check if its cached or not must take some time.
Would I be best off including my JS inline in the ascx files, or code behind, directly inserting the script, or what is the 'correct' way to handle these multiple files to reduce get requests from the browser.
I'm using CSS sprites for buttons and stuff for the same reason, so wondering what to do with JS files. In my case CSS is generally handled by classes in the primary pages, so these are not an issue.
We actually built a control on top of ScriptManager that automatically extracts all of the js from all controls on a page, including scriptresource.axd and stores them in a single cached file. This has greatly improved performance and reduced maintenance work since it is automated. We built this starting in .Net 2.0, so I am not sure if ScriptManager now provides the same functionality, but I thought it was worth mentioning.
Here is our implementation of this class:
Option Explicit On
Option Strict On
Imports System.Collections.Generic
Imports System.Web.SessionState
Public Class OurScriptManager
Inherits ScriptManager
Implements IRequiresSessionState
Private m_ScriptBuilder As New StringBuilder
'Private m_sSessionIndex As String = ""
Private m_cScripts As List(Of ScriptReference)
Private m_fIsCached As Boolean
Private m_sScriptName As String = ""
Private m_sScriptFileName As String = ""
Const CACHED_SCRIPTS_DIR As String = "/scriptcache/"
Public Sub New()
' default constructor
End Sub
Public Property ScriptName() As String
Get
Return m_sScriptName
End Get
Set(ByVal value As String)
m_sScriptName = value
End Set
End Property
Private ReadOnly Property ScriptFileName() As String
Get
If String.IsNullOrEmpty(m_sScriptFileName) Then
m_sScriptFileName = "~" & CACHED_SCRIPTS_DIR & Me.ScriptName & ".js"
End If
Return m_sScriptFileName
End Get
End Property
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
' Exceptions are handled by the caller
MyBase.OnInit(e)
If String.IsNullOrEmpty(Me.ScriptName) Then
Me.ScriptName = Me.Page.ToString
End If
' this compiled script should be cached on the server
' check for the file, if it exists, load that file instead of generating it
If Configuration.HasPageScriptBeenCached(Me.ScriptFileName) AndAlso File.Exists(Me.Page.Server.MapPath(Me.ScriptFileName)) Then
m_fIsCached = True
Else
m_cScripts = New List(Of ScriptReference)
End If
End Sub
Protected Overrides Sub OnResolveScriptReference(ByVal e As System.Web.UI.ScriptReferenceEventArgs)
Try
MyBase.OnResolveScriptReference(e)
If Not m_fIsCached Then
' First, check to make sure this script should be loaded
Dim fIsFound As Boolean
For Each oXref As ScriptReference In m_cScripts
If oXref.Assembly = e.Script.Assembly AndAlso oXref.Name = e.Script.Name AndAlso oXref.Path = e.Script.Path Then
fIsFound = True
Exit For
End If
Next
' If this script is found within the list of scripts that this page uses, add the script to the scripthandler.aspx js output
If Not fIsFound Then
Dim oReference As ScriptReference
Dim oElement As ScriptReference
Dim fIsPathBased As Boolean
oElement = e.Script
If String.IsNullOrEmpty(oElement.Path) AndAlso Not String.IsNullOrEmpty(oElement.Name) AndAlso String.IsNullOrEmpty(oElement.Assembly) Then
' If resource belongs to System.Web.Extensions.dll, it does not
' provide assembly info that's why hard-coded assembly name is
' written to get it in profiler
oElement.Assembly = "System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
End If
'check to see what type of script this is
If Not String.IsNullOrEmpty(oElement.Path) Then
' this script is a physical file
oReference = New ScriptReference(oElement.Path)
fIsPathBased = True
ElseIf Not String.IsNullOrEmpty(oElement.Assembly) AndAlso Not String.IsNullOrEmpty(oElement.Name) Then
' this script is generated by an assembly
oReference = New ScriptReference(oElement.Name, oElement.Assembly)
Else
' Couldn't find script, so bail to allow standard processing to take place.
Return
End If
If Not fIsPathBased Then
Dim sUrl As String
Dim oRequest As HttpRequest
Dim sScriptResourcePath As String
sUrl = GetUrl(oReference)
sScriptResourcePath = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}", Context.Request.Url.Scheme, "://", Context.Request.Url.Host, ":", Context.Request.Url.Port, "/", Context.Request.ApplicationPath, "/ScriptResource.axd")
oRequest = New HttpRequest("scriptresource.axd", sScriptResourcePath, sUrl.Substring(sUrl.IndexOf("?"c) + 1))
Try
Using oWriter As New StringWriter(m_ScriptBuilder)
Dim oHandler As IHttpHandler = New System.Web.Handlers.ScriptResourceHandler
oHandler.ProcessRequest(New HttpContext(oRequest, New HttpResponse(oWriter)))
End Using
Catch theException As Exception
Call ReportError(theException)
' Since we couldn't automatically process this, just bail so that standard processing takes over
Return
End Try
Else
' If this script is from a file, open the file and load the
' contents of the file into the compiled js variable
Dim sAbsolutePath As String
sAbsolutePath = Context.Server.MapPath(oElement.Path)
Try
If System.IO.File.Exists(sAbsolutePath) Then
Using oReader As New StreamReader(sAbsolutePath, True)
m_ScriptBuilder.Append(oReader.ReadToEnd())
End Using
Else
Throw New Exception("File " & sAbsolutePath & " does not exist")
End If
Catch theException As Exception
Call ReportError(theException, New ExtraErrorInformation("File", sAbsolutePath))
' Since we couldn't automatically process this, just bail so that standard processing takes over
Return
End Try
End If
m_ScriptBuilder.AppendLine()
' add this script to the script reference library
Dim oNewElement As New ScriptReference
oNewElement.Name = e.Script.Name.ToString()
oNewElement.Assembly = e.Script.Assembly.ToString()
oNewElement.Path = e.Script.Path.ToString()
m_cScripts.Add(oNewElement)
End If
End If
' a script filename is provided for caching
e.Script.Assembly = String.Empty
e.Script.Name = String.Empty
e.Script.Path = Me.ScriptFileName
Catch theException As Exception
HttpContext.Current.Response.Write(ReportError(theException))
HttpContext.Current.Response.End()
End Try
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
' Exceptions are handled by the caller
MyBase.Render(writer)
If Not m_fIsCached Then
If Not String.IsNullOrEmpty(Me.ScriptName) Then
' Save script to file for caching
Using fsFile As New FileStream(Me.Page.Server.MapPath(Me.ScriptFileName), FileMode.Create, FileAccess.Write, FileShare.Read)
Using oWriter As New StreamWriter(fsFile)
oWriter.Write(m_ScriptBuilder.ToString)
oWriter.Flush()
oWriter.Close()
End Using
fsFile.Close()
End Using
' Record that the script file has been cached
Configuration.RecordPageScriptCached(Me.ScriptFileName)
End If
m_ScriptBuilder = Nothing
End If
End Sub
Private Function GetUrl(ByVal oReference As ScriptReference) As String
' Exceptions are handled by the caller
If String.IsNullOrEmpty(oReference.Path) Then
Try
Dim oMethod As MethodInfo
oMethod = oReference.GetType.GetMethod("GetUrl", BindingFlags.NonPublic Or BindingFlags.Instance)
If oMethod IsNot Nothing Then
Return DirectCast(oMethod.Invoke(oReference, New Object() {Me, False}), String)
Else
Return String.Empty
End If
Catch ex As Exception
Return String.Empty
End Try
Else
Return Me.ResolveClientUrl(oReference.Path)
End If
End Function
End Class
In the above code, ReportError logs the exception to the event log and/or file; you can replace this with your own mechanism.
Here is the Configuration code:
Private Shared m_cCachedPageScripts As Collections.Generic.List(Of String)
''' <summary>
''' This method is used to determine whether or not the script for the page has been cached.
''' This is used for script combining.
''' </summary>
''' <param name="sKey"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function HasPageScriptBeenCached(ByVal sKey As String) As Boolean
' Exceptions are handled by the caller
SyncLock CacheSyncObject
If m_cCachedPageScripts IsNot Nothing AndAlso m_cCachedPageScripts.Contains(sKey) Then
Return True
End If
End SyncLock
End Function
''' <summary>
''' This method is used to record the fact that the page script has been cached.
''' This is used for script combining.
''' </summary>
''' <param name="sKey"></param>
''' <remarks></remarks>
Public Shared Sub RecordPageScriptCached(ByVal sKey As String)
' Exceptions are handled by the caller
SyncLock CacheSyncObject
If m_cCachedPageScripts Is Nothing Then
m_cCachedPageScripts.Add(sKey)
End If
m_cCachedPageScripts.Add(sKey)
End SyncLock
End Sub
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :
Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate
Try
Dim uri As New Uri(args.Value)
Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
Dim response As HttpWebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As String = New StreamReader(stream).ReadToEnd()
args.IsValid = True
Catch ex As Exception
args.IsValid = False
End Try
End Sub
I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".
What is wrong with this code ?
Update :
I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)
function testURLValide(sender, args)
{
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open("HEAD", args.Value, false);
xmlhttp.send(null);
if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
I put your code into LINQPad and tested it out and it worked just fine...
The only difference is args.Value.
Dim uri As New Uri("http://www.google.com")
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(uri)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As String = New StreamReader(stream).ReadToEnd()
reader.Dump()
<!doctype html><html><head><meta
http-equiv="content-type"
content="text/html;
charset=ISO-8859-1"><title>Google</title>............
Why not use WebClient.DownloadString() method instead?
Instead of reading the stream, how about testing for the HTTP Status Code? I believe it is response.StatusCode. The value you would look for would be 200, or possibly something in the 300s (redirect).
If you can use javascript, here's one really good way to do it: How to Test a URL in jQuery
Edit: How about one of these approaches then?
Search for "Does a URL exist?" on this page.
How to check if a URL exists in javascript
Javascript to check if URL exist
I am making a page that accepts post data from any number of pages that I cannot change, access, or in any way control.
I need, in one way or another, to get the timezone of the user. I know, ideally the posting page would do this, but I cannot access these pages.
I've read other answers on this site and come up with 2 almost, but not quite there solutions.
First, there is javascript. I can get the javascript function to return (or change a label to) the correct value, but the problem is I need this info before the postback. I've been trying to write the timezone name on another page and read that page, but I have no idea how to begin to do that? Any other workaround to use the javascript is welcome, or any way to force call this before Page_Load is called?
function getTimeZone()
{
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
var label = document.getElementById("<%=TZ.ClientID%>");
label.textContent = "GMT " + gmtHours;
}
The second solution is to read it from another page, and I am using this:
http://ipinfodb.com/ip_query.php?ip=192.36.167.120&timezone=true
(Completely random ip in there, btw)
So here is my function to get the info from that site:
public string GetTimezone(string ip)
{
string address = string.Format("http://ipinfodb.com/ip_query.php?ip={0}&timezone=true", ip);
string timezone = "";
try
{
XmlTextReader reader = new XmlTextReader(address);
HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(address);
wrq.Proxy.Credentials = CredentialCache.DefaultCredentials;
reader = new XmlTextReader(wrq.GetResponse().GetResponseStream());
string lastRead = "";
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
lastRead = reader.Name;
}
if (reader.NodeType == XmlNodeType.Text)
{
if (string.Compare(lastRead, "TimezoneName", true) == 0)
{
timezone = reader.Value;
break;
}
}
}
}
catch
{
timezone = "";
}
return timezone;
}
Basically, this works in debug mode, but when it's live only an empty string is returned. I am baffled? Is there any better way to read data from a page? I am using Request.ServerVariables["REMOTE_ADDR"] to get the ip, and that seems to be correct, since it inserts the correct ip into the database I'm using.
Here is the call:
GetTimezone(Request.ServerVariables["REMOTE_ADDR"]);
You're getting an exception, probably because of a trust issue / firewall on the production server.
Get rid of the evil catch block so you can find out what the exception is.