SMS HTTP API call from ASP.NET is slow - asp.net

For a web application, I am creating a SMS module that can send an SMS from the application. My SMS provider has an API that I can call over HTTP.
The API is called via an XmlTextReader who just reads the XML response from the API.
Now my problem is: When I send the SMS from a web page (basically just doing an HTTP request) it takes more than a minute before I receive the SMS.
But when I run the exact same code from a Windows console application, my SMS arrives in less then 5 seconds.
I have done multiple tests with this, and it's not really my SMS provider who is slow.
Somehow, the HTTP request gets delayed from within the ASP.NET engine, and it does not delay directly from an console application. Is there a solution?
This is the way I'm calling the HTTP API:
Dim strPostString As String = Convert.ToString(muriPostUrl) & mstrPostPath
If mblnUseSecureConnection Then
strPostString = Convert.ToString(muriSecurePostUrl) & mstrPostPath
End If
Dim strDataString As String = "username=" & mstrUsername
strDataString += "&" & "password=" & mstrPassword
strDataString += "&" & "originator=" & mstrOriginator
strDataString += "&" & "recipients=" & mstrRecipients
strDataString += "&" & "gateway=" & mstrGateway
strDataString += "&" & "reference=" & mstrReference
strDataString += "&" & "message=" & mstrMessage
If mstrType <> String.Empty Then
strDataString += "&" & "type=" & mstrType
End If
If mstrUDH <> String.Empty Then
strDataString += "&" & "udh=" & mstrUDH
End If
If Not mdtDeliveryDate = Nothing Then
Dim objDeliveryDate As New StringBuilder()
objDeliveryDate.Append(mdtDeliveryDate.Year)
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Month.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Day.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Hour.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Minute.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Second.ToString(), 2))
strDataString += "&" & "deliverydate=" & Convert.ToString(objDeliveryDate)
End If
Dim strReturnValue As String = ""
Dim xmlReader As New XmlTextReader(String.Format("{0}?{1}", strPostString, strDataString))
While xmlReader.Read()
If xmlReader.NodeType = XmlNodeType.Element Then
Select Case xmlReader.LocalName
Case "recipients"
If True Then
mintSuccessCount = Integer.Parse(xmlReader.ReadString())
strReturnValue += "recipients : " & mintSuccessCount.ToString() & vbCr & vbLf
Exit Select
End If
Case "success"
If True Then
mblnSuccess = Boolean.Parse(xmlReader.ReadString())
strReturnValue += "success : " & mblnSuccess.ToString() & vbCr & vbLf
Exit Select
End If
Case "resultcode"
If True Then
mintResultCode = Integer.Parse(xmlReader.ReadString())
strReturnValue += "resultcode : " & mintResultCode.ToString() & vbCr & vbLf
Exit Select
End If
Case "resultmessage"
If True Then
mstrResultMessage = xmlReader.ReadString()
strReturnValue += "resultmessage : " & mstrResultMessage & vbCr & vbLf
Exit Select
End If
End Select
End If
End While
Also, when performing an HTTP request from ASP.NET, it does not appear in Fiddler, while the actual HTTP request happens. How can I track the HTTP fastback from within the ASP.NET engine?
I still don't know what the problem is, but I worked around it by doing the postback via an HttpWebRequest directly. I think the problem was somewhere in the while loop.

Related

How to get a list of running processes in Classic ASP? [duplicate]

I need a VBScript that will check if a process is in use by a specific user:
Agent clicks program icon --> batch file calls for progcheck.vbs -->
progcheck.vbs looks to see is "whatever.exe" is running under that user only -->
if program is running under that user then MsgBox "Program running" --> wscript.quit (this needs to terminate out of the batch file)
else --> return to batch file.
I have tried this with tasklist in a batch file and the script works, but takes forever to run for a domain user. Want to do this in vbscript anyway.
*** UPDATED SCRIPT WITH MODS 10/12 *****
OPTION EXPLICIT
DIM strComputer,strProcess, strUserName,wshShell
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
strComputer = "." '
strProcess = "notepad.exe"
IF isProcessRunning(strComputer,strProcess,strUserName) THEN
If MsgBox ("Notepad needs to be closed.", 1) = 1 then
wscript.Quit(1)
End If
END IF
FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName,BYVAL strUserName)
DIM objWMIService, strWMIQuery
strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "' AND owner like '" &strUserName& "'"
SET objWMIService = GETOBJECT("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN
isProcessRunning = TRUE
ELSE
isProcessRunning = FALSE
END If
End Function
Let me know what you think and where I have it wrong. Thanks in advance.
UPDATED CODE v3: review comments for help
OPTION EXPLICIT
DIM strComputer, strProcess, strUserName, wshShell
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
strComputer = "."
strProcess = "notepad.exe" 'change this to whatever you are trying to detect
IF isProcessRunning(strComputer, strProcess, strUserName) THEN
If MsgBox ("Notepad needs to be closed.", 1) = 1 then
wscript.Quit(1) 'you need to terminate the process if that's your intention before quitting
End If
Else
msgbox ("Process is not running") 'optional for debug, you can remove this
END IF
FUNCTION isProcessRunning(ByRef strComputer, ByRef strProcess, ByRef strUserName)
DIM objWMIService, strWMIQuery, objProcess, strOwner, Response
strWMIQuery = "SELECT * FROM Win32_Process WHERE NAME = '" & strProcess & "'"
SET objWMIService = GETOBJECT("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery(strWMIQuery)
IF objWMIService.Count > 0 THEN
msgbox "We have at least ONE instance of Notepad"
For Each objProcess in objWMIService
Response = objProcess.GetOwner(strOwner)
If Response <> 0 Then
'we didn't get any owner information - maybe not permitted by current user to ask for it
Wscript.Echo "Could not get owner info for process [" & objProcess.Name & "]" & VBNewLine & "Error: " & Return
Else
Wscript.Echo "Process [" & objProcess.Name & "] is owned by [" & strOwner & "]" 'for debug you can remove it
if strUserName = strOwner Then
msgbox "we have the user who is running notepad"
isProcessRunning = TRUE
Else
'do nothing as you only want to detect the current user running it
isProcessRunning = FALSE
End If
End If
Next
ELSE
msgbox "We have NO instance of Notepad - Username is Irrelevant"
isProcessRunning = FALSE
END If
End Function
You can use the following function:
FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName)
DIM objWMIService, strWMIQuery
strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "'"
SET objWMIService = GETOBJECT("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN
isProcessRunning = TRUE
ELSE
isProcessRunning = FALSE
END IF
END FUNCTION
For local computer you would use "."
For the process name, you would use the executable "notepad.exe"
For the rest of the code, you could can use something simple:
OPTION EXPLICIT
DIM strComputer,strProcess
strComputer = "." ' local computer
strProcess = "notepad.exe" 'whatever is the executable
IF isProcessRunning(strComputer,strProcess) THEN
'do something
ELSE
'do something else or nothing
wscript.echo strProcess & " is NOT running on computer '" & strComputer & "'"
END IF
That should do it.
EXTRA
To show every process running, then just run:
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strList
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process")
For Each objProcess in colProcess
strList = strList & vbCr & _
objProcess.Name
Next
WSCript.Echo strList
WScript.Quit
in terminal server this function can be very slow, all the GetOwner calls are terrible in performance.
A very fast solution i created is to narrow the query using SessionID of the current user (assuming we want only current user's processes) So I added this code:
SessionID can be obtained this way:
Dim oExec, sOutput, iUserPos, iUserLen, iStatePos, SessionID
dim oShell, userName
Set oShell = CreateObject("Wscript.Shell")
userName = oShell.ExpandEnvironmentStrings("%USERNAME%")
Set oExec = oShell.Exec("query session %username%")
sOutput = LCase(oExec.StdOut.ReadAll)
iUserPos = InStr(sOutput, LCase(userName))
iStatePos = InStr(sOutput, "active")
iUserLen = Len(userName)
SessionID = CInt(Trim(Mid(sOutput, iUserPos+iUserLen, iStatePos-iUserPos-iUserLen)))
Changed the function from the previous post:
Function isProcessRunning(ByRef strComputer, ByRef strProcess, ByRef strUserName, byRef sessionID)
DIM objWMIService, strWMIQuery, objProcess, strOwner, Response
strWMIQuery = "SELECT * FROM Win32_Process WHERE SessionId = " & sessionID & " And NAME = '" & strProcess & "'"
SET objWMIService = GETOBJECT("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery(strWMIQuery)
IF objWMIService.Count > 0 THEN
'msgbox "We have at least ONE instance of Notepad"
For Each objProcess in objWMIService
Response = objProcess.GetOwner(strOwner)
If Response = 0 Then
'Wscript.Echo "Process [" & objProcess.Name & "] is owned by [" & strOwner & "]" 'for debug you can remove it
if strUserName = strOwner Then
'msgbox "we have the user who is running notepad"
isProcessRunning = TRUE
Else
'do nothing as you only want to detect the current user running it
isProcessRunning = FALSE
End If
'else
'we didn't get any owner information - maybe not permitted by current user to ask for it
'Wscript.Echo "Could not get owner info for process [" & objProcess.Name & "]" & VBNewLine & "Error: " & Return
End If
Next
ELSE
'msgbox "We have NO instance of Notepad - Username is Irrelevant"
isProcessRunning = FALSE
END If
End Function

Exporting Json data in asp.net vb from MS SQL

I am trying to export data from MS SQL out in a json format in my asp.net web forms application. Problem is it exports with two double quotes around the values instead of just one double quote.
I want it to export like this:
{"bizunitid":"11111","prodlineid":"1","reasonforsurvey":"1"}
but it is coming out like this:
"{""bizunitid"":""11111"",""prodlineid"":""1"",""reasonforsurvey"":""2""}"
I have tried replacing the two double quotes but it always returns two double quotes.
Dim json As String = cmd.ExecuteScalar
streamWriter.Write(json.Replace("""""", Chr(34)))
Not sure if this is what you're looking for, but it's how I've done it when posting JSon to an API for a messaging app with VB.Net:
MessageTitle = MessageTitle.Replace("""", """""")
MessageBody = MessageBody.Replace("""", """""")
Dim strPostData As String = "{" &
"""notification"": {" &
"""sound"": ""default""," &
"""title"": """ & MessageTitle & """," &
"""body"": """ & MessageBody & """" &
"}, " &
"""data"": {" &
"""title"": """ & MessageTitle & """," &
"""body"": """ & MessageBody & """" &
"}," &
"""to"": """ & strRegIDs & """," &
"""priority"": 10 " &
"}"
hopefully that helps a bit

File.Create not working in asp.net

It might be a little funny but I am facing some stupid issue.
I am using
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
and
Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
when I using this the error is given to me is "Could not find a part of the path "
If am storing the path in a string then its working fine else producing error.
For your reference I am copying my function code snippet.
Please help
Thanks
Public Shared Function LogErrorToLogFile(ByVal ee As Exception, ByVal userFriendlyError As String) As String
Try
Dim path As String = context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))
' check if directory exists
If Not Directory.Exists(path) Then
'Directory.CreateDirectory(path)
Directory.CreateDirectory(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
End If
path = path & DateTime.Today.ToString("dd-MMM-yy") & ".log"
' check if file exist
If Not File.Exists(path) Then
File.Create(path).Dispose()
'File.Create(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))).Dispose()
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
End If
' log the error now
Using writer As StreamWriter = File.AppendText(path)
'Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
writer.WriteLine(HttpUtility.HtmlEncode(vbCr & vbLf & "Log written at : " & DateTime.Now.ToString() & vbCr & vbLf & "Error occured on page : " & context.Current.Request.Url.ToString() & vbCr & vbLf & vbCr & vbLf & "Here is the actual error :" & vbLf & ee.ToString()))
writer.WriteLine("==========================================")
writer.Flush()
writer.Close()
End Using
Return userFriendlyError
Catch
Throw
End Try
End Function
If you change the current lines with the comment-outed lines in your function code snippet, you're logic is changed because when you use Path, there is added a filename [dd-MMM-yy].log to the path-string. but you don't use that addition when you use the ConfigurationManager.AppSettings("LogFilePath1") directly!
I assume that you have not used the folder path with slash (ex: #"C:\FolderName\") and that is the reason you are getting the error.

Incorrect syntax near the keyword 'close'

I have a section of code in one of my scripts that is getting an error in its syntax.
if(status <> true and Request.QueryString("selectId") = "undefined") then
strConn ="PROVIDER=foobar;Server=foo;Database=foo;Uid=bar;Pwd=bar;"
Set cnt = Server.CreateObject("ADODB.Connection")
set rs1 = CreateObject("ADODB.Recordset")
rs1.CursorLocation = adUseClient
cnt.ConnectionString= strConn
cnt.Open strConn
sql="Select * from rule1 where skucode='" & Request.Form("txthidden") & "' and letter1id ='" & Request.Form("lrt1") & "' and letter2id ='" & Request.Form("Select1") & "' and letter3id ='" & Request.Form("Select2") & "'"
rs1.Open sql,cnt,2,2
if not rs1.EOF then
Response.write("<script language=""javascript"">alert('Rules already exists!');</script>")
else
sql="INSERT INTO rule1 (letter1id,letter2id,letter3id,HTML,skucode) VALUES "
sql=sql & "('" & Request.Form("lrt1") & "',"
sql=sql & "'" & Request.Form("Select1") & "',"
sql=sql & "'" & Request.Form("Select2") & "',"
sql=sql & "'" & Request.Form("txthtml") & "',"
sql=sql & "'" & Request.Form("txthidden") & "')"
cnt.Execute sql
Response.write("<script language=""javascript"">alert('Rules Added successfully!');window.location='" & "viewrule1.asp?skucodes=" & Request.Form("txthidden") & "';</script>")
end if
rs1.Close
cnt.close
The error message I get is:
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'close'.
/path/file.asp, line 75
Instead of closing it, you can detach it completely:
set cnt = Nothing
There shouldn't be a problem. All i think is if your data is too long or not. Sometimes it occurs when your row limit exceeds. SQL Server 6.5 allows a maximum row size of 1962 bytes and SQL Server 7.0 allows a maximum row size of 8060 bytes. Its just an assumption
Presuming it's the last line that's throwing the error, I'd replace it with:
If IsObject(cnt) Then
On Error Resume Next
If cnt.State = 1 Then ' 1 = adStateOpen '
cnt.Close
End If
Set cnt = Nothing
Err.Clear
On Error Goto 0
End If
cnt is probably already closed by the time it reaches that portion of your script which is why it's throwing the error. Checking its status before closing it needs to be wrapped in On Error Resume Next logic, otherwise it'll throw another error.

How to Validate a textbox+dropdowns in vb for a asp.net form

Previous question which links onto this and has any addition code ref should I forget to link any, I have set it up to email me should someone submit this form and an error occur and right now should that occur for most integer or datetime fields if they fail to validate then it will show me which fields in the email failed and what was input into them.
Problem I'm having now is to validate the drop downs and the textboxs in a similar way to what I with integer and datetime fields so I can display those also in the email in case they error.
present integer and datetime validation
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine).Replace(vbNewLine, "<br />" + vbNewLine)
Dim dtb As DateTime
If Not DateTime.TryParse(DateOfBirth, dtb) Then
strEMessageBody.Append("<strong>Date Of Birth:</strong> " & DateOfBirthYear.SelectedItem.Value & "-" & DateOfBirthMonth.SelectedItem.Value & "-" & DateOfBirthDay.SelectedItem.Value & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
Dim iao As Integer
If Not Integer.TryParse(AnyOther, iao) Then
strEMessageBody.Append("<strong>Any Other:</strong> " & rblAnyOther.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
then below the final validation I have the Dim for the email setting but that I sorted out in the other question.
The problem is much earlier in the page I have
Sub Upload_Click(ByVal source As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
Dim Name As String
Which prevents me just using there names as shown above where I would instead call them something else but that doesn't work with strings so my main issue is having some bit of code to check if the strings are valid and for the dropdowns which would either work but always show the data in the email or would hiccup in the code,
Dim imd As Integer
If Not Integer.TryParse(dept, imd) Then
strEMessageBody.Append("<strong>Department:</strong> " & dept.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
below was how it had been setup to record the department
Department = dept.SelectedItem.Value
Department = Replace(Department, "'", "''")
Summary:- Need vb code to validate if strings and dropdowns are valid and the use of try/catch block is another possible solution but I wasn't able to figure out how to implement validation for that either.
Log your values into your database. Setup a logging table called "tblLog" or something else. Record the value of ex.Message or possibly even InnerException (if it exists).
Going hand in hand with Matt's answer, there is a tool that can help you with automatically logging errors to a DB.
It's called ELMAH.
EDIT
Here are 2 validations that you might want to use:
Dim s As String = "some user input in here"
If [String].IsNullOrEmpty(s) Then
' Watch out, string is null or it is an empty string
End If
Dim cb As New ComboBox()
If cb.SelectedItem Is Nothing Then
' Watch out, combo has no item selected
End If
NOTE ComboBox is a WinForm control in this example, but the idea is the same for the ASP.NET counterpart
Since everybodies given up trying to find a solution then I'm just gona close this topic with this post as the answer.

Resources