Hot to call to ASP.NET file from VBS file? - asp.net

How can I call to a ASP.NET file (.aspx) from a VBS file that are both on the SAME server ?
I need that the VBS file will execute the asp.net file with some parameters.
Thanks

something like this?
Dim ie
Set ie = CreateObject("internetexplorer.app location")
ie.Navigate "http://www.mysite.com/mypage.aspx?q=1"
ie.Visible=True
or
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "iexplore http://www.mysite.com/mypage.aspx?q=1", 9
WScript.Sleep 10000 ' Give ie some time to load
'Close the browser
WshShell.SendKeys "%F"
WshShell.SendKeys "C"
or
rebember that you run web pages directly from the Task Scheduler and use curl

You can use ServerXMLHttp:-
dim xhr : set xhr = CreateObject("MSXML2.ServerXMLHttp.3.0")
xhr.open "GET", "http://yoursite/youcode.ashx?params=x", false
xhr.send
if xht.status = 200 then
msgbox "Success :)"
else
msgbox "Failed :("

You can use the following in your .vbs file
Set winHttpRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
winHttpRequest.Open "GET", "http://localhost/mypage.aspx", false
winHttpRequest.Send
WScript.Echo(winHttpRequest.GetAllResponseHeaders())
WScript.Echo(winHttpRequest.ResponseText)
For more examples, see http://www.neilstuff.com/winhttp/
You should be able to call any URL (including .aspx pages) on your server (or on the internet)

Related

Connecting to google - R and VBA

I am trying to connect to google using R but I'm having some issues with the proxy/auth settings. Using VBA all I have to run is the below which works fine:
Function GetResult(url As String) As String
Dim XMLHTTP As Object, ret As String
Set XMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.4.0")
XMLHTTP.Open "GET", url, False
XMLHTTP.send
ret = XMLHTTP.responseText
GetResult = ret
End Function
Sub Example()
'Print the HTML of Google.com
Debug.Print GetResult("http://www.google.com")
End Sub
In R, if I run the following:
library('rvest')
url <- 'http://google.com'
webpage <- read_html(url,verbose=TRUE)
I get
Error in open.connection(x, "rb") :
Timeout was reached: Connection timed out after 10000 milliseconds
There is an issue with the proxy settings that is being used in R. Is there a way I can figure out what proxy settings VBA is using in excel and use those in R?
Check your proxy settings : https://helpdeskgeek.com/networking/internet-connection-problem-proxy-settings/
Then configure the proxy in R
proxy = paste0("http://",LOGIN,":",PASSWORD,"#,"PROXY_ADRESS,":8080")
Sys.setenv(http_proxy = proxy)
Sys.setenv(https_proxy = proxy)

Microsoft (REST/GRAPH) Authorization Using ASP.NET WebForms VB.NET

Nearing a month working on this with little success, any help would be appreciated a lot.
I have to get calendar items from outlook accounts. Managed to get it to work in ASP.NET MVC with C#, ported the code over to VB.NET on ASP.NET WebForms, but with no success.
I can only find code samples and authorization methods that work with MVC, but the application I have to implement it in still uses WebForms (aspx pages)
I've tried both the Microsoft Restful API and the Graph API, but they both only seem to support MVC. Same thing with the authorization methods they require, (Azure AD v1, v2, oauth, sdk)
Any suggestions?
The Graph Client library may not support the webForm(VB.net), but the Restful Graph API should works well. The restful Graph API can be used by almost any language or framework . For VB.NET on ASP.NET WebForms, because it is not recommended/supported by the official now, so many logic we need to handle by ourselves(HttpClient) or use 3rd lib.
Just one vb.net sample for your reference, ignore the WebForms itself, just copy the code to where you need and modify the logic to what you want.
https://www.example-code.com/vbnet/microsoft_graph_oauth2_access_token.asp
Dim oauth2 As New Chilkat.OAuth2
Dim success As Boolean
' This should be the port in the localhost callback URL for your app.
' The callback URL would look like "http://localhost:3017/" if the port number is 3017.
oauth2.ListenPort = 3017
oauth2.AuthorizationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
oauth2.TokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
' Replace these with actual values.
oauth2.ClientId = "MICROSOFT-GRAPH-CLIENT-ID"
' This is your app password:
oauth2.ClientSecret = "MICROSOFT-GRAPH-CLIENT-SECRET"
oauth2.CodeChallenge = False
' Provide a SPACE separated list of scopes.
' See https://developer.microsoft.com/en-us/graph/docs/authorization/permission_scopes
' Important: To get a refresh token in the final response, you have to ask for "offline_access" scope
oauth2.Scope = "openid profile offline_access user.readwrite mail.readwrite mail.send"
' Begin the OAuth2 three-legged flow. This returns a URL that should be loaded in a browser.
Dim url As String = oauth2.StartAuth()
If (oauth2.LastMethodSuccess <> True) Then
Debug.WriteLine(oauth2.LastErrorText)
Exit Sub
End If
' At this point, your application should load the URL in a browser.
' For example,
' in C#: System.Diagnostics.Process.Start(url);
' in Java: Desktop.getDesktop().browse(new URI(url));
' in VBScript: Set wsh=WScript.CreateObject("WScript.Shell")
' wsh.Run url
' in Xojo: ShowURL(url) (see http://docs.xojo.com/index.php/ShowURL)
' The Microsoft account owner would interactively accept or deny the authorization request.
' Add the code to load the url in a web browser here...
' Add the code to load the url in a web browser here...
' Add the code to load the url in a web browser here...
' Now wait for the authorization.
' We'll wait for a max of 30 seconds.
Dim numMsWaited As Integer = 0
While (numMsWaited < 30000) And (oauth2.AuthFlowState < 3)
oauth2.SleepMs(100)
numMsWaited = numMsWaited + 100
End While
' If there was no response from the browser within 30 seconds, then
' the AuthFlowState will be equal to 1 or 2.
' 1: Waiting for Redirect. The OAuth2 background thread is waiting to receive the redirect HTTP request from the browser.
' 2: Waiting for Final Response. The OAuth2 background thread is waiting for the final access token response.
' In that case, cancel the background task started in the call to StartAuth.
If (oauth2.AuthFlowState < 3) Then
oauth2.Cancel()
Debug.WriteLine("No response from the browser!")
Exit Sub
End If
' Check the AuthFlowState to see if authorization was granted, denied, or if some error occurred
' The possible AuthFlowState values are:
' 3: Completed with Success. The OAuth2 flow has completed, the background thread exited, and the successful JSON response is available in AccessTokenResponse property.
' 4: Completed with Access Denied. The OAuth2 flow has completed, the background thread exited, and the error JSON is available in AccessTokenResponse property.
' 5: Failed Prior to Completion. The OAuth2 flow failed to complete, the background thread exited, and the error information is available in the FailureInfo property.
If (oauth2.AuthFlowState = 5) Then
Debug.WriteLine("OAuth2 failed to complete.")
Debug.WriteLine(oauth2.FailureInfo)
Exit Sub
End If
If (oauth2.AuthFlowState = 4) Then
Debug.WriteLine("OAuth2 authorization was denied.")
Debug.WriteLine(oauth2.AccessTokenResponse)
Exit Sub
End If
If (oauth2.AuthFlowState <> 3) Then
Debug.WriteLine("Unexpected AuthFlowState:" & oauth2.AuthFlowState)
Exit Sub
End If
Debug.WriteLine("OAuth2 authorization granted!")
Debug.WriteLine("Access Token = " & oauth2.AccessToken)
' Get the full JSON response:
Dim json As New Chilkat.JsonObject
json.Load(oauth2.AccessTokenResponse)
json.EmitCompact = False
' The JSON response looks like this:
' {
' "token_type": "Bearer",
' "scope": "User.Read Mail.ReadWrite Mail.Send",
' "expires_in": 3600,
' "ext_expires_in": 0,
' "access_token": "EwBAA8l6B...",
' "refresh_token": "MCRMdbe...",
' "id_token": "eyJ0eXA..."
' }
' If an "expires_on" member does not exist, then add the JSON member by
' getting the current system date/time and adding the "expires_in" seconds.
' This way we'll know when the token expires.
If (json.HasMember("expires_on") <> True) Then
Dim dtExpire As New Chilkat.CkDateTime
dtExpire.SetFromCurrentSystemTime()
dtExpire.AddSeconds(json.IntOf("expires_in"))
json.AppendString("expires_on",dtExpire.GetAsUnixTimeStr(False))
End If
Debug.WriteLine(json.Emit())
' Save the JSON to a file for future requests.
Dim fac As New Chilkat.FileAccess
fac.WriteEntireTextFile("qa_data/tokens/microsoftGraph.json",json.Emit(),"utf-8",False)
Another reference for handle the logic by our self but not 3rd lib.
Accessing imgUr thru OAuth (uploading to user account)

Classic ASP : Capture Errors

Is it possible to capture all 500 errors in Classic ASP at a global level? Maybe something in IIS. I'm using II6 at the moment. I like to capture the error message and then store it in the database. I know its possible in ASPX pages, but don't know exactly how you do in classic asp.
Thank you
Yes, create an asp page which will log the error details to the database, and set this to be the 500 handler page in IIS as below.
Use the Server.GetLastError object to get the details of the error in your handler script.
It might be a good idea to log to a text file rather than a DB in your 500 handler for resiliency.
Complementing Jon's answer, use this script to write errors to a log file:
<%
'Set this page up in IIS to receive HTTP 500 errors
''Type' needs to be 'URL' and the URL is e.g.: '/500Error.asp' if this file is named '500Error.asp' and is in the site root directory.
'This script assumes there is a "/Log" folder, and that IIS has write access to it.
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim objFSO, err
Set objFSO=CreateObject("Scripting.FileSystemObject")
Set err = Server.GetLastError()
outFile=Server.MapPath("/Log/ErrorLog.txt")
Set objFile = objFSO.OpenTextFile(outFile, ForAppending, True, TristateTrue)
objFile.WriteLine Now & " - ERROR - ASPCode:" & err.ASPCode & " ASPDescription: " & err.ASPDescription & " Category: " & err.Category & " Description: " & err.Description & " File: " & err.File & " Line: " & err.Line & " Source: " & err.Source & vbCrLf
objFile.Close
Set objFile = Nothing
Set err = Nothing
%>
Error handling in classic ASP is a complete pain. You can catch the error where you think it's going to occur using on error resume next, then check for the error code in the following line of code.
Alternately you can scan the server logs for 500 errors. or set up a "500 error" page in your IIS settings.
On Error Resume Next
... do something...
If Err.Number <> 0 Then
... handle error
end if
To add to #Jon Eastwood's answer - if you are using IIS 7.5, then instead of "Custom errors" you will look for ".NET Error Pages" per the image below:
This applies to Windows Server 2008 and other newer Windows SKUs.

Error in class referring - CDONTS

I get an error at the following line in my application:
'create NewMail object'
Line 96: Function SendHTMLEMail (strFrom, strTo, strCC, strSubject, strBodyHTML)
Line 97: Set objNewMail = Server.CreateObject("CDONTS.NewMail")
The error is:
Error Type:
Server object, ASP 0177 (0x800401F3)
Invalid class string
/Utils.inc, line 97
I have added interop.CDONTS.dll to the references of application, but still I am getting same error.
I am not sure if this functionality is used in any other page and is working.
I use .NET 2003 framework 1.1, and the server is running Windows Server 2003
ASP-Classic
Since CDONTS is discontinued since Win2000 and newer you should switch to CDOSYS.
Sample code for sending via remote server
Set oMessage = CreateObject("CDO.Message")
Set oConfig = CreateObject("CDO.Configuration")
Set oFields = oConfig.Fields
With oFields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.acme.com"
.Update
End With
With oMessage
Set .Configuration = oConfig
.To = "recipient#acme.com"
.From = "sender#acme.com"
.Subject = "A Subject Line"
.TextBody = "A Text body message"
.Fields.Update
.Send
End With
The linked site features detailed examples for all kinds of scenarios.
ASP.NET
If you are targeting ASP.NET you should use System.Net.Mail instead of CDO
I got the solution. I added a new CDONTS.dll and registered it using
regsvr32 C:\SYSROOT\system32\cdonts.dll
This solved the problem. No need of adding it to the references.

Checking if another web server is listening from asp

I'm using Microsoft.XMLHTTP to get some information from another server from an old ASP/VBScript site. But that other server is restarted fairly often, so I want to check that it's up and running before trying to pull information from it (or avoid my page from giving an HTTP 500 by detecting the problem some other way).
How can I do this with ASP?
You could try making a ping to the server and check the response.
Take a look at this article.
All you need to do is have the code continue on error, then post to the other server and read the status from the post. Something like this:
PostURL = homelink & "CustID.aspx?SearchFlag=PO"
set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.3.0")
on error resume next
xmlhttp.open "POST", PostURL, false
xmlhttp.send ""
status = xmlhttp.status
if err.number <> 0 or status <> 200 then
if status = 404 then
Response.Write "ERROR: Page does not exist (404).<BR><BR>"
elseif status >= 401 and status < 402 then
Response.Write "ERROR: Access denied (401).<BR><BR>"
elseif status >= 500 and status <= 600 then
Response.Write "ERROR: 500 Internal Server Error on remote site.<BR><BR>"
else
Response.write "ERROR: Server is down or does not exist.<BR><BR>"
end if
else
'Response.Write "Server is up and URL is available.<BR><BR>"
getcustomXML = xmlhttp.responseText
end if
set xmlhttp = nothing

Resources