Keeps getting EOF expected error - asp.net

I have this problem with SOAP that I can't seem to solve.
No matter what I try, then I keep getting this error:
500 - Internal server error. There is a problem with the resource you
are looking for, and it cannot be displayed.
When digging further down the error code I'm told there is a EOF expected error?
Hope that some of you might be able to help me
<%
On Error Resume Next
Dim objXMLHTTP : set objXMLHTTP = Server.CreateObject("Msxml2.XMLHTTP.3.0")
Dim strFunction
Dim strRequest
Dim strResult
Dim strName
Dim strFirstName
Dim strLastname
Dim strAddress
Dim strZipCode
Dim strCity
Dim strTelephone
Dim strTelephone2
Dim strTelephone3
Dim strTelephone4
Dim strEmail
Dim strExtFields
Dim strStdFields
Dim CampaignID
Dim Page
Page = Request.Form("Page")
CampaignID = Request.Form("CampaignID")
StrName = Request.Form("Name")
StrTelephone = Request.Form("Phone")
strRequest = ""
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"">
<Body>
<InsertNewCustomer xmlns=""http://api.ivocall.dk/ivocallservice.asmx"">
<Login>Loginname</Login>
<Password>Password</Password>
<ClientID>1323</ClientID>
<IDPassword>ag4bghsitm8gatddbpt34qjndjrbsla</IDPassword>
<CampaignID>"& campaignid &"</CampaignID>
<Name>"& StrName &"</Name>
<Firstname></Firstname>
<Lastname></Lastname>
<Address></Address>
<City></City>
<ZipCode></ZipCode>
<Telephone>"& StrTelephone &"</Telephone>
<Telephone2></Telephone2>
<Telephone3></Telephone3>
<Telephone4></Telephone4>
<email></email>
<ExtFields>landingpage="& page &"</ExtFields>
<StdFields></StdFields>
<UserName></UserName>
</InsertNewCustomer>
</Body>
</Envelope>"
objXMLHTTP.open "post", "" & "http://api.ivocall.dk/ivocallservice.asmx" & "", False
objXMLHTTP.setRequestHeader "Content-Type", "text/xml; charset=UTF-8"
objXMLHTTP.setRequestHeader "Content-Length", Len(strRequest)
objXMLHTTP.setRequestHeader "SOAPAction", "http://www.ivocall.dk/ivocallservice/InsertNewCustomer"
'send the request and capture the result
Call objXMLHTTP.send(strRequest)
strResult = objXMLHTTP.responseText
'display the XML
response.write strResult
response.write strRequest
If Err.Number <> 0 Then
Response.Write (Err.Description)
ELSE
Response.Write ("task done")
Response.End
End If
%>
I really hope some of you can help me out her?

You use inline code-tags.
<%
They do not contain any imported namespaces.
Additionally, you seem to want to copying XML into strRequest, but you're not properly escaping it, plus VB.NET (which is what you're using, not C#) doesn't support multiline strings.
And why do you use
Server.CreateObject("Msxml2.XMLHTTP.3.0")
You can use the normal WebRequest class, instead of an ActiveX-Object. And if you want to do it client-side, you need to use JavaScript (AJAX).
If you're doing a cross-domain request, you need to use CORs (and a browser supporting CORs), or you need to write a proxy that does the request for you.
Additionally, did you try adding a web-reference to your project ?
Visual Studio will automagically download the WSDL and generate the wrapper classes. Why do you want to do it by hand ? ...
Additionally, if you want to embed code in the ASPX page, do it in a "script"-tag using runat="server":
<%# Register TagPrefix="RS" Namespace="Microsoft.ReportingServices.WebServer" Assembly="ReportingServicesWebServer" %>
<%# Page Language="C#" AutoEventWireup="true" Inherits="Microsoft.ReportingServices.WebServer.ReportViewerPage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<script type="text/C#" runat="server">
protected void SetDocumentMode()
{
if(System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.Browser == null || System.Web.HttpContext.Current.Request.Browser.Browser == null)
// return "<null>";
return;
if (!StringComparer.OrdinalIgnoreCase.Equals(System.Web.HttpContext.Current.Request.HttpMethod, "GET"))
// return "<notget>";
return;
// fu IE 11
if(System.Web.HttpContext.Current.Request.Browser.Browser == "IE" || System.Web.HttpContext.Current.Request.Browser.Browser == "InternetExplorer")
{
if(System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(System.Convert.ToString(System.Web.HttpContext.Current.Request.QueryString), "stylesheet", System.Globalization.CompareOptions.IgnoreCase) == -1 )
{
System.Web.HttpContext.Current.Response.Write(#"<meta http-equiv='X-UA-Compatible' content='IE=5'>
");
//return "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=5\">"; // IE5-Quirks when no custom stylesheet (=not in iframe)
}
else
System.Web.HttpContext.Current.Response.Write("<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>");
// return "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">"; // Switch to Standards mode when a custom stylesheet is set(=in iframe)
}
// return "<not ie: " + System.Web.HttpContext.Current.Request.Browser.Browser + ">";
//return "";
}
</script>
[...]
<%SetDocumentMode(); %>
Are you actually using ASP instead of ASP.NET ?

Related

Download file works on firefox, not on other browsers

in staging my download function is working fine, when I deploy in production (nas server with IIS 7.5) the same functions works only on Firefox.
With IE, Edge and Chrome the download start but, it don't arrive to the end, and after minute, get an error.
I know that there is a lot of documentation online but I just tried a lot of solutions without result. Please help me.
#Page Language="VB" ContentType="text/html"
#Import Namespace="System.Data"
#Import Namespace="System.Data.SqlClient"
#Import Namespace="System.IO"
Private SUB SDataBind()
'Path construction
Dim VarFileName as string = "mytest.zip"
'Path construction
Dim VarPath as string = "/public/mydownload" & VarFileName
'Absolute path
Dim VarCompletPath as string = Server.MapPath(VarPath)
VarCompletPath = replace(VarCompletPath,"/","\")
'Filename construction
Dim VarLast4Char as string = right(VarFileName,4)
Dim VarNewFilename as string = "download" & VarLast4Char
'Headers cleaner
Response.Clear
Response.ClearHeaders
Response.ClearContent
'Send the file to the browser
Response.AddHeader("Content-Disposition", ("attachment;filename=" & VarNewFilename))
Response.ContentType = ReturnFiletype( right(VarFileName,4) )
Response.WriteFile( VarCompletPath )
Response.Flush()
Response.Close()
Response.End
end sub
'----------------------------
'Get content file type
Private function ReturnFiletype(fileExtension as string) as string
Select Case fileExtension
case ".zip"
return "application/zip"
case ".pdf"
return "application/pdf"
case else
return "application/octet-stream"
end select
end function
I resolved with a more classic function
'Clean the headers
Response.Clear
Response.ClearHeaders
Response.ClearContent
'Send file to browser
Response.AddHeader("Content-Disposition", ("attachment;filename=" & VarFileName))
Response.WriteFile(Server.MapPath(VarPath))
Response.End
I removed the lines
Response.Flush()
Response.Close()

New Google Recaptcha with ASP.Net

I am attempting to get the new Google reCaptcha working in my ASP.NET project and I am having problems getting it to be the new one "I'm not a robot".
I had the old one in there and after doing much research on the developers.google.com web site, everything looks the same (they even point me to a download of the same dll - 1.0.5). So, I got the new keys and put them in and it works but it looks just like the old reCaptcha.
Has anyone gotten the new one to work with their ASP.Net? What am I missing?
EDIT:
So playing around in a test app and searching some other web sites I found that if I create a page like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form id="form1" runat="server" action="?" method="POST">
<div>
<div class="g-recaptcha" data-sitekey="My Public Key"></div>
<br/>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
And then in my code-behind (Button1_Click), I do this:
Dim Success As Boolean
Dim recaptchaResponse As String = request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Success = True
Else
Success = False
End If
The recaptchaResponse will either be empty or filled in depending on if they are a bot or not. The issue is, I now need to take this response and send it to google with my private key so I can verify that the response was not provided by a bot, in my code-behind, but I cannot figure out how. I tried this (in place of Success = True):
Dim client As New System.Net.Http.HttpClient()
client.BaseAddress = New Uri("https://www.google.com/recaptcha/")
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
Dim response As Net.Http.HttpResponseMessage = Await client.GetAsync("api/siteverify?secret=My Private key&response=" + recaptchaResponse)
If (response.IsSuccessStatusCode) Then
Dim CaptchResponse As ReCaptchaModel = Await response.Content.ReadAsAsync(Of ReCaptchaModel)()
Success = CaptchResponse.success
Else
Success = False
End If
But, I could not figure out how to get the async stuff working and I cannot find anything on what ReCaptchaModel is, so I found another way to call a web service and get a json response and tried this instead:
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/")
Dim Data As String = "api/siteverify?secret=My Private Key&response=" + recaptchaResponse
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = "{""data"":""" + Data + """}"
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
'get response-stream, and use a streamReader to read the content
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
Stop
End Using
End Using
But, this just gives me the content of the web page at https://www.google.com/recaptcha. Not what I want. The Google page isn't very useful and I am stuck on where to go. I need some help either calling the Google verify service or if anyone has found another way to do this from ASP.NET.
I had just about given up when I ran across something unrelated that made me think about it again and in a different way. In my last attempt above, I was attempting to pass the private key and recaptcha response as the data, so I tried it in the create of the WebRequest and it worked. Here is the final solution:
Using the same HTML posted above, I created a function that I can call in the button click event where I check the Page.IsValid and call this function:
Private Function IsGoogleCaptchaValid() As Boolean
Try
Dim recaptchaResponse As String = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=My Private Key&response=" + recaptchaResponse)
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = ""
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
''get response-stream, and use a streamReader to read the content
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
If jsonData = "{" & vbLf & " ""success"": true" & vbLf & "}" Then
Return True
End If
End Using
End Using
End If
Catch ex As Exception
'Dont show the error
End Try
Return False
End Function
I'm sure there are improvements to be made to the code, but it works. I couldn't see adding references to some JSON libraries for reading one thing I just check the string.
Thank you for sharing this. It worked for me. I went ahead and converted it to C# (since that's what I was using) and added a few things.
I changed the validation step. I split the JSON string and evaluated if success was found where it should be.
I used the ConfigurationManager to store the ReCaptcha Keys.
Finally, I changed it from using a WebRequest to using and HttpClient. This cut the code in half because I don't need to read the stream now.
Feel free to use this code as well.
private static bool IsReCaptchaValid(string response)
{
if (string.IsNullOrWhiteSpace(response))
{
return false;
}
var client = new HttpClient();
string result =
client.GetStringAsync(string.Format("{0}?secret={1}&response={2}", ConfigurationManager.AppSettings["ReCaptchaValidationLink"],
ConfigurationManager.AppSettings["ReCaptchaSecretKey"], response)).Result;
string[] split = result.Split('\"');
return split[1] == "success";
}
I took a slightly different approach, using the data-callback option and a Session parameter. The following sits within the MainContent block of the .aspx file:
<asp:ScriptManager ID="scrEnablePage" EnablePageMethods="true" runat="server" />
<asp:Panel ID="pnlCaptcha" runat="server" Visible="true">
<div class="g-recaptcha"
data-sitekey='<asp:Literal ID="litKey" runat="server" Text="<%$ AppSettings:recaptchaPublicKey%>" />'
data-callback="handleCaptcha"></div>
</asp:Panel>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript">
function handleCaptcha(e) {
PageMethods.RecaptchaValid(e);
location.reload(true);
}
</script>
Then in the code-behind:
Private Const GoogleUrl As String = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
pnlCaptcha.Visible = Not (Session("VerifiedHuman") = "True")
...
End Sub
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Sub RecaptchaValid(response As String)
Dim client As New System.Net.WebClient()
Dim outcome As Dictionary(Of String, String)
Dim result As String = String.Join(vbCrLf,
{"{", """success"": true", "}"})
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim url As String = String.Format(GoogleUrl,
ConfigurationManager.AppSettings.Get("recaptchaPrivateKey"),
response)
Try
result = client.DownloadString(url)
Catch ex As System.Net.WebException
Exit Sub ' Comment out to default to passing
End Try
outcome = serializer.Deserialize(Of Dictionary(Of String, String))(result)
HttpContext.Current.Session("VerifiedHuman") = outcome("success")
End Sub
Now in Page_Load you can check Session("VerifiedHuman") = "True" and update your page controls accordingly, hiding the panel with the Captcha control and showing the other appropriate items.
Note that this takes the keys from Web.config, i.e.
<configuration>
<appSettings>
<add key="recaptchaPublicKey" value="..." />
<add key="recaptchaPrivateKey" value="..." />
...
</appSettings>
...
</configuration>
This adds a few things. It converts the response from Google into a Json object, it adds a timeout on the verification request, and it adds a verification of the hostname (required by Google if sending requests from multiple domains and the domains aren't listed in the Google Admin area).
Imports Newtonsoft.Json
Public Class Google
Public Class ReCaptcha
Private Const secret_key = "YOUR_SECRET_KEY"
Public Shared Function Validate(Request As HttpRequest, hostname As String) As Boolean
Dim g_captcha_response = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(g_captcha_response) Then
Dim response = ExecuteVerification(g_captcha_response)
If Not response.StartsWith("ERROR:") Then
Dim json_obj = JsonConvert.DeserializeObject(Of ValidateResponse)(response)
If json_obj.success Then
If json_obj.hostname.ToLower = hostname.ToLower Then Return True
End If
End If
End If
Return False
End Function
Private Shared Function ExecuteVerification(g_captcha_response As String) As String
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" & secret_key & "&response=" & g_captcha_response)
request.Timeout = 5 * 1000 ' 5 Seconds to avoid getting locked up
request.Method = "POST"
request.ContentType = "application/json"
Try
Dim byteArray As Byte() = Encoding.UTF8.GetBytes("")
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As Net.WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
Return "ERROR: " & ex.Message
End Try
End Function
Public Class ValidateResponse
Public Property success As Boolean
Public Property challenge_ts As DateTime
Public Property hostname As String
<JsonProperty("error-codes")>
Public Property error_codes As List(Of String)
End Class
End Class
End Class
So in the button's Click event, just call:
If Google.ReCaptcha.Validate(Request, Request.Url.Host) Then
' good to go
Else
' validation failed
End If

Google reCAPTCHA Validation Issue (accepts anything including blank)

I'm attempting to implement Google's reCAPTCHA on a Classic ASP site and am attempting to follow the guidelines outline here:
https://developers.google.com/recaptcha/docs/asp
Following the instructions on that page, I've added this code to the top of the page that contains the form:
<%
recaptcha_challenge_field = Request("recaptcha_challenge_field")
recaptcha_response_field = Request("recaptcha_response_field")
recaptcha_public_key = "<font color=red>your_public_key</font>" ' your public key
recaptcha_private_key = "<font color=red>your_private_key</font>" ' your private key
' returns the HTML for the widget
function recaptcha_challenge_writer()
recaptcha_challenge_writer = _
"<script type=""text/javascript"">" & _
"var RecaptchaOptions = {" & _
" theme : 'red'," & _
" tabindex : 0" & _
"};" & _
"</script>" & _
"<script type=""text/javascript"" src=""http://www.google.com/recaptcha/api/challenge?k=" & recaptcha_public_key & """></script>" & _
"<noscript>" & _
"<iframe src=""http://www.google.com/recaptcha/api/noscript?k=" & recaptcha_public_key & """ frameborder=""1""></iframe><br>" & _
"<textarea name=""recaptcha_challenge_field"" rows=""3""cols=""40""></textarea>" & _
"<input type=""hidden"" name=""recaptcha_response_field""value=""manual_challenge"">" & _
"</noscript>"
end function
' returns "" if correct, otherwise it returns the error response
function recaptcha_confirm(rechallenge,reresponse)
Dim VarString
VarString = _
"privatekey=" & recaptcha_private_key & _
"&remoteip=" & Request.ServerVariables("REMOTE_ADDR") & _
"&challenge=" & rechallenge & _
"&response=" & reresponse
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttp.open "POST", "http://www.google.com/recaptcha/api/verify", False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send VarString
Dim ResponseString
ResponseString = split(objXmlHttp.responseText, vblf)
Set objXmlHttp = Nothing
if ResponseString(0) = "true" then
'They answered correctly
recaptcha_confirm = ""
else
'They answered incorrectly
recaptcha_confirm = ResponseString(1)
end if
end function
server_response = ""
newCaptcha = True
if (recaptcha_challenge_field <> "" or recaptcha_response_field <> "") then
server_response = recaptcha_confirm(recaptcha_challenge_field, recaptcha_response_field)
newCaptcha = False
end if
%>
Also per that page, I've added this code to the form itself to generate the reCAPTCHA widget:
<% if server_response <> "" or newCaptcha then %>
<% if newCaptcha = False then %>
<!-- An error occurred -->
Wrong!
<% end if %>
<%=recaptcha_challenge_writer()%>
<% else %>
<!-- The solution was correct -->
Correct!
<%end if%>
I can get the CAPTCHA to display properly, but it isn't verifying - it will accept any answer including being left blank. I believe some of the code needs to be added to my script that actually handles the data, but am not sure which code or where to put it.
I've tried moving portions of the above code that appear to be for validation purposes to the script that processes the responses and generates an e-mail, but have had no luck there either.
The for page can be viewed here:
http://www.onlyproforma.com/mktimg/landingPage_ResultsFirst4_CAPTCHA.asp
I am aware there are other options, but I would like to get this one working if possible.
Any help is greatly appreciated.
I had a similar issue especially with the NEW reCAPTCHA tick functionality. If you look at the reCAPTCHA admin site which gives you your public and private (secret) keys, you'll see that the server side integration URL to verify, is different from the code above. In the code above, the verify URL is _http://www.google.com/recaptcha/api/verify whereas the verify URL supplied by the reCAPTCHA admin page is _https://www.google.com/recaptcha/api/siteverify. Very different.
Also, the parameters required are different. In the above code, there is a call for Request("recaptcha_challenge_field") and Request("recaptcha_response_field"). Yet the new reCAPTCHA verify only requires the response field. But even that has changed! It is now request.form("g-recaptcha-response").
Granted, the code that you are using above comes straight from Google themselves (https://developers.google.com/recaptcha/old/docs/asp). But it appears that this code is outdated, especially if you consider that it is filed in a directory called OLD.
So this is what worked for me!
Dim recaptcha_secret
recaptcha_secret = "your secret code"
Dim sendstring
sendstring = _
"https://www.google.com/recaptcha/api/siteverify?" & _
"secret=" & recaptcha_secret & _
"&response=" & request.form("g-recaptcha-response")
Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXML.Open "GET", sendstring , false
objXML.Send()
The code below reads the response from Google. The reply comes back as a JSON object, but I cannot read or process the JSON response on the server-side and I could not find an easy method.
So the workaround was to search for the string 'true'. If it returned TRUE (positive) then the reCAPTCHA was confirmed. If it does not return TRUE, then the response is essentially
FALSE and the reCAPTCHA was not submitted correctly.
It is ugly but it works:
if instr(objXML.responseText,"true") then
response.redirect "to an appropriate page"
else
response.redirect "to an appropriate page"
end if
Maybe there is a neater way to read the Google reply, but I have tested it and it works for me.
The full code then would look like this:
<%
Dim recaptcha_secret
recaptcha_secret = "your secret code"
Dim sendstring
sendstring = _
"https://www.google.com/recaptcha/api/siteverify?" & _
"secret=" & recaptcha_secret & _
"&response=" & request.form("g-recaptcha-response")
Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXML.Open "GET", sendstring , false
objXML.Send()
if instr(objXML.responseText,"true") then
response.redirect "to an appropriate page"
else
response.redirect "to an appropriate page"
end if
%>
The following code will go in the page where the form is posted. i.e. in your case L_Landing_actionJCR.asp
<% if server_response <> "" then %>
Wrong!
<% else %>
Correct!
<% else %>

Server.CreateObject(“Scripting.FileSystemObject”) issue - Object required:Server (code:0) ASP/VBscript

I want to create a file on my server, and then, write datas in
<script runat="server" language="VBScript">
Function saveData()
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("ecr.txt", 8,true)
f.WriteLine("osgfouds")
End Function
</script>
I get an error in my browser telling me 'object required: server' at the 'Server.CreateObject' line
Server.createobject would be for VBScript/ASP scripts on the server itself. The client browser would not be able to support Server for this reason.
As an added note. You need to Close out your file object(f) because it will keep the file open and cause errors when you try to write to it again. Also, I added the ForAppending bit so that you can specify it in your fso.opentextfile.
So to fix your script:
<script runat="server" language="VBScript">
Function saveData()
Const ForReading As String = 1
Const ForWriting As String = 2
Const ForAppending As String = 8
Dim fso as Object
Dim f as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("ecr.txt", ForAppending, true)
f.WriteLine("osgfouds")
f.Close
End Function
</script>
EDIT
This is an updated question from -> Here
EDIT
Ok, looking at your previous question and this one. Here's the thing: ASP runs at the server level and Loads vbscript into the website interface. Vbscript attached directly to ASP will run at the server level:
e.g.
<%
Const ForAppending = 8
dim fn,fp,fpn,wl,fulltext : fn = replace(formatdatetime(Now, 2), "/", "-") & ".txt"
Dim fso, msg : fp = "C:\Users\...\Desktop\Logs\"
fpn = fp & fn
dim sep : sep = "==========================================================================="&vbcrlf
dim ssep : ssep = vbcrlf & "--------------------------------------"
fso = CreateObject("Scripting.FileSystemObject")
dim IPAddress, HostName, LUname
IPAddress = Request.ServerVariables("remote_addr")
If (fso.FileExists("C:\Users\...\Desktop\Logs\" & fn)) Then
dim inSession,newuser
wl = fso.OpenTextFile(fpn, ForAppending, True)
inSession = fso.OpenTextFile("C:\Users\...\Desktop\Logs\" & fn, 1)
fulltext = inSession.ReadAll
'.....Code continues'
%>
So if your trying to activate a click event and attach it to a VBScript to write to a file on the server end, this will not work, because the vbscript will attempt to write it to the client regardless.
The proper way for a asp/vbscript to be designed for user entry updates needs to be executed in the following fashion:
BROWSER - click -> request to server -> server processes request -> serves new page -> BROWSER
Evidence provided -> Here
However, you can still utilize an XMLHTTPRequest or Ajax/Javascript to activate a script. Actually, funny thing is, I just asked about how to execute a very basic script like this recently. So here's how to do it:
You have your HTML file(whatever.html):
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type ="text/javascript" >
$(function () {
$("#button").click(function () {
$.get("test2.aspx", {
loadData: "John"
})
.done(function (data) {
if (data === "Fail") {
alert("Logging Failed!");
} else {
alert("Logged Success!");
}
})
.fail(function () {
alert("error");
});
});
});
</script>
</head><body>
<input type="button" id="button" value="Ecriture"></body>
And you have your ASPX File (test2.aspx):
<%# Page Language="VB" %>
<%
Dim LogData As String : LogData = Request.Params("loadData")
Dim SaveFile As String
Const ForReading As Integer = 1
Const StorageDirectory = "C:\Users\...\Desktop\Logs\serverlog.txt"
Const ForWriting As Integer = 2
Const ForAppending As Integer = 8
If Len(LogData) = 0 Then LogData = "{EMPTY STRING}"
Dim fso As Object
Dim f As Object
fso = CreateObject("Scripting.FileSystemObject")
f = fso.OpenTextFile(StorageDirectory, ForAppending, True)
f.WriteLine("New Entry:" & LogData)
f.Close()
If Err.Number <> 0 Then
SaveFile = "Fail"
Else
SaveFile = "Success"
End If
Response.Write(SaveFile)
%>
NOTE
The StorageDirectory must be a shared network folder so that the server can maintain updating the file.
I've tested this code and it works. Good Luck
This will work in VB.NET. Try this
Dim oFs
Dim vSharePath
Dim vFolder
Dim vPath
Dim objTStream
vSharePath = ConfigurationManager.AppSettings("NetworkPath").ToString
vFolder = Year(Date.Now) & Month(Date.Now).ToString & Date.Now.Hour.ToString & Date.Now.Second.ToString
vPath = vSharePath & "\" & vFolder
oFs = Server.CreateObject("Scripting.FileSystemObject")
If Not (oFs.FolderExists(vPath)) Then
Call oFs.CreateFolder(vPath)
objTStream = oFs.CreateTextFile(vPath & "\test.txt", True)
'Write some text to the file
objTStream.WriteLine("Hello World!")
objTStream.WriteLine()
objTStream.WriteLine("This is my first text file!")
'Close the TextStream object
objTStream.Close()
'Free up resources
objTStream = Nothing
End If
oFs = Nothing
http://webcheatsheet.com/asp/filesystemobject_object.php

Using reCAPTCHA with Classic ASP

I'm trying to use this example of classic ASP but I have 2 pages, one is form page, the other is verify page. I'm a total newb at classic ASP so I'm not sure if I'm making some syntax errors or not.
https://developers.google.com/recaptcha/docs/asp
On my form page, I'm loading reCAPTCHA via JS and that part is working fine. On the verify page, I have the code below.
Main code (I removed stuff from Google that I wasn't going to use like generate a recaptcha form field with ASP)
recaptcha_challenge_field = Request.Form("recaptcha_challenge_field")
recaptcha_response_field = Request.Form("recaptcha_response_field")
recaptcha_public_key = "hidden" //your public key
recaptcha_private_key = "hidden" //your private key
// returns "" if correct, otherwise it returns the error response
function recaptcha_confirm(rechallenge,reresponse)
Dim VarString
VarString = _
"privatekey=" & recaptcha_private_key & _
"&remoteip=" & Request.ServerVariables("REMOTE_ADDR") & _
"&challenge=" & rechallenge & _
"&response=" & reresponse
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttp.open "POST", "http://www.google.com/recaptcha/api/verify", False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send VarString
Dim ResponseString
ResponseString = split(objXmlHttp.responseText, vblf)
Set objXmlHttp = Nothing
if ResponseString(0) = "true" then
'They answered correctly
recaptcha_confirm = ""
else
'They answered incorrectly
recaptcha_confirm = ResponseString(1)
end if
end function
server_response = ""
newCaptcha = True
if (recaptcha_challenge_field <> "" or recaptcha_response_field <> "") then
server_response = recaptcha_confirm(recaptcha_challenge_field, recaptcha_response_field)
newCaptcha = False
end if
This is where I'm trying to detect if captcha is correct, but it submits form either way.
if recaptcha_response_field <> "" AND newCaptcha = False then
// submit form
Else
Response.Write "Error: Please fill out all form fields correctly."
End If
Well looks like I had to do it this way:
If server_response = "" AND newCaptcha = False then
// Captcha correct
ElseIf server_response <> "" OR newCaptcha then
// Captcha incorrect
Else
// Some other form error
End If

Resources