Classic ASP inserting variable value into Access DB - html

I am trying to insert a variable value into my access database, I am able to insert a value that's pre-set like
<td width="125" nowrap="nowrap" ><div align="right">Lead From </div></td>
<td><input name="lead" type="text" id="lead" value="" size="50" /></td>
as you can see we have a id of "lead" and I can insert that into the db fine like this:
MM_fieldsStr = "lead|value";
MM_columnsStr = "Lead|',none,''";
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(Request.Form(MM_fields(MM_i)))
Next
now I want to be able to do something like this:
Session("MM_JobNumber") = job_number
MM_fieldsStr = job_number & "|value"
MM_columnsStr = "Job_Num|',none,''"
when ever i try pass a variable through it returns null, ofc you cant see job number being set in the code i have supplied but it does 100% get set.
COUNTER RECORDER::
Dim countrec
Dim countrec_numRows
Set countrec = Server.CreateObject("ADODB.Recordset")
countrec.ActiveConnection = MM_JobConn_STRING
countrec.Source = "SELECT * FROM CounterTAB WHERE Counter_ID = 1"
countrec.CursorType = 0
countrec.CursorLocation = 2
countrec.LockType = 1
countrec.Open()
countrec_numRows = 0
FULL CODE BELOW::
If (CStr(Request("MM_insert")) = "form2") Then
Dim job_number
IF (Session("MM_JobNumber") <> "") OR (Session("MM_JobNumber") <> NULL)Then
job_number = Session("MM_JobNumber")
Else
Dim new_count_num
new_count_num = countrec.Fields.Item("Counter_NUM").Value+1
job_number = PadDigits(new_count_num, 4) + "-" + mid(DatePart("yyyy",now()),3,2)
Session("MM_JobNumber") = job_number
END IF
'UPDATE COUNTER
set counterupdate = Server.CreateObject("ADODB.Command")
counterupdate.ActiveConnection = MM_JobConn_STRING
counterupdate.CommandText = "UPDATE CounterTAB SET Counter_NUM = Counter_NUM + 1 WHERE Counter_ID = 1"
counterupdate.CommandType = 1
counterupdate.CommandTimeout = 0
counterupdate.Prepared = true
counterupdate.Execute()
MM_editConnection = MM_JobConn_STRING
MM_editTable = "Job_Details"
MM_editRedirectUrl = "view_jobs_new.asp?offset=-1"
MM_fieldsStr = job_number & "|value|hiddenDateRaised|value|hiddenYearRaised|value|hiddenNewRaisedBYID|value|hiddenRaisedBYID|value|hiddenFieldCompanyID|value|hiddenFieldContact1|value|Job_Ref_Name|value|checkbox3_1|value|checkbox3_15|value|checkbox3_4|value|checkbox3_2|value|checkbox3_16|value|checkbox3_5|value|checkbox3_3|value|checkbox3_6|value|checkbox3_7|value|checkbox3_22|value|checkbox3_8|value|checkbox3_9|value|checkbox3_23|value|checkbox3_10|value|checkbox3_20|value|checkbox3_11|value|checkbox3_17|value|checkbox3_12|value|checkbox3_21|value|checkbox3_13|value|checkbox3_18|value|checkbox3_24|value|checkbox3_14|value|checkbox3_19|value|checkbox3_25|value|checkbox3_26|value|DescriptText|value|sitename|value|siteAdd1|value|siteAdd2|value|siteAdd3|value|siteAdd4|value|siteAdd5|value|sitePostCode|value|lead|value"
MM_columnsStr = "Job_Num|',none,''|Job_Date|',none,''|Job_Year|none,none,NULL|New_Raised_By|none,none,NULL|Raised_By|none,none,NULL|Company|none,none,NULL|Contact|none,none,NULL|Job_Ref|',none,''|Scope_3_01_SiteDecom|none,-1,0|Scope_3_15_Spill|none,-1,0|Scope_3_04_TankClean|none,-1,0|Scope_3_02_SiteClosure|none,-1,0|Scope_3_16_EnviroAss|none,-1,0|Scope_3_05_OtherTankClean|none,-1,0|Scope_3_03_GroundRem|none,-1,0|Scope_3_06_TankLining|none,-1,0|Scope_3_07_TankPainting|none,-1,0|Scope_3_22_SaleFuel|none,-1,0|Scope_3_08_ShipTank|none,-1,0|Scope_3_09_VapourRec|none,-1,0|Scope_3_23_SaleRec|none,-1,0|Scope_3_10_Petroscope|none,-1,0|[Scope_3_20_IBC Testing]|none,-1,0|Scope_3_11_Vacutect|none,-1,0|Scope_3_17_FuelSys|none,-1,0|Scope_3_12_TankCalib|none,-1,0|Scope_3_21_FuelSampling|none,1,0|Scope_3_13_5stage|none,-1,0|Scope_3_18_Oftec|none,-1,0|Scope_3_24_SpillKit|none,-1,0|Scope_3_14_Rail|none,-1,0|Scope_3_19_TankerServices|none,-1,0|Scope_3_25_Training|none,-1,0|Scope_3_26_Other|none,-1,0|Job_Description|',none,'' | Site_Name|',none,''|Site_Add1|',none,''|Site_Add2|',none,''|Site_Add3|',none,''|Site_Add4|',none,''|Site_Add5|',none,''|Site_Postcode|',none,''|Lead_From|',none,''"
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(Request.Form(MM_fields(MM_i)))
Next
' append the query string to the redirect URL
If (MM_editRedirectUrl <> "" And Request.QueryString <> "") Then
If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And Request.QueryString <> "") Then
MM_editRedirectUrl = MM_editRedirectUrl & "?" & Request.QueryString
Else
MM_editRedirectUrl = MM_editRedirectUrl & "&" & Request.QueryString
End If
End If
End If
INSERT CODE::
' *** Insert Record: construct a sql insert statement and execute it
Dim MM_tableValues
Dim MM_dbValues
If (CStr(Request("MM_insert")) <> "") Then
'here goes counter update
' create the sql insert statement
MM_tableValues = ""
MM_dbValues = ""
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_formVal = MM_fields(MM_i+1)
MM_typeArray = Split(MM_columns(MM_i+1),",")
MM_delim = MM_typeArray(0)
If (MM_delim = "none") Then MM_delim = ""
MM_altVal = MM_typeArray(1)
If (MM_altVal = "none") Then MM_altVal = ""
MM_emptyVal = MM_typeArray(2)
If (MM_emptyVal = "none") Then MM_emptyVal = ""
If (MM_formVal = "") Then
MM_formVal = MM_emptyVal
Else
If (MM_altVal <> "") Then
MM_formVal = MM_altVal
ElseIf (MM_delim = "'") Then ' escape quotes
MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
Else
MM_formVal = MM_delim + MM_formVal + MM_delim
End If
End If
If (MM_i <> LBound(MM_fields)) Then
MM_tableValues = MM_tableValues & ","
MM_dbValues = MM_dbValues & ","
End If
MM_tableValues = MM_tableValues & MM_columns(MM_i)
MM_dbValues = MM_dbValues & MM_formVal
Next
MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"
If (Not MM_abortEdit) Then
' execute the insert
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_editConnection
MM_editCmd.CommandText = MM_editQuery
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
Session("MM_JobNumber") = NULL
If (MM_editRedirectUrl <> "") Then
Response.Redirect(MM_editRedirectUrl)
End If
End If
End If

Split() deals with separators, not delimiters. So the trailing "|" in
MM_columnsStr = "Job_Num|',none,''|"
causes a spurious/empty element in the array. Evidence:
>> s = "Lead|',none,''"
>> a = Split(s, "|")
>> WScript.Echo UBound(a), a(UBound(a))
>>
1 ',none,''
>> s = "Job_Num|',none,''|"
>> a = Split(s, "|")
>> WScript.Echo UBound(a), a(UBound(a))
>>
2
On second thought:
This
>> job_number = "JN"
>> MM_fieldsStr = job_number & "|value"
>> WScript.Echo MM_fieldsStr
>>
JN|value
should prove, that string concatenation works in VBScript. If you get
|value
then job_number is empty before the & line. Perhaps you meant
job_number = Session("MM_JobNumber")
instead of
Session("MM_JobNumber") = job_number
Last thought:
This:
IF (Session("MM_JobNumber") <> "") OR (Session("MM_JobNumber") <> NULL)Then
job_number = Session("MM_JobNumber")
will set job_number only if is not empty or Null.

all that was needed was to pad the job_number string out with ' ' marks at the start and end, hope this helps anyone else trying to do something similar

Related

how to display long text ( datatype text up to 20 000 characters) in div

I'm currently enhancing a system using vb.net. My issue is, i need to display a column name 'WONOTE' (datatype TEXT) from SQL Server into div in html front screen. The maximum length of characters for this column is up to 22 000 characters. I retrieved the data from SQL server into div by using sql command in code behind. I manage to display the data but only up to 110 characters by using this statement 1:
REPLACE(REPLACE(cast(WONOTE as varchar(110)), CHAR(13), ''), CHAR(10), '')
and up to 10 characters using this statement 2:
CONVERT(VARCHAR(10), b.WONOTE) as WONOTE
but I need it to display full text. If i change into varchar(max) or anything greater than 110 for statement 1 and 10 for statement 2 it display nothing.
I wish someone can help me with it.
Thank you in advance.
How i retrieved data from SQL server:
Public Sub GETWHATSRUNNING()
Dim paraWC As SqlParameter
Dim SQL As String
Dim myArray, myArray1, myArray2, myArray3,
myArray4, myArray5, myArray6, myArray7,
myArray8, myArray9, myArray10 As String
TempDT.Columns.Add("WO", GetType(String))
TempDT.Columns.Add("WOQTY", GetType(String))
TempDT.Columns.Add("PartNum", GetType(String))
TempDT.Columns.Add("Desc", GetType(String))
TempDT.Columns.Add("WIPQTY", GetType(String))
TempDT.Columns.Add("WIPDAYS", GetType(String))
TempDT.Columns.Add("WOAGING", GetType(String))
TempDT.Columns.Add("AGINGATWC", GetType(Double))
TempDT.Columns.Add("COLOR", GetType(String))
'TempDT.Columns.Add("WO_NOTE", GetType(String))
WCLimit = 5
SQL = "select distinct A.WONO, B.BLDQTY , C.PART_NO , C.DESCRIPT, B.Start_Date, REPLACE(REPLACE(cast(WONOTE as varchar(110)), CHAR(13), ''), CHAR(10), '') " & _
"from Transfer A " & _
"left join WOENTRY B on A.wono = B.wono " & _
"left join INVENTOR C on B.UNIQ_KEY = C.UNIQ_KEY " & _
"where FR_DEPT_ID = #WC and start_date is not null " & _
"and B.BLDQTY <> B.COMPLETE "
GetConnection()
oConnSql = New SqlConnection(connString.ToString)
oCmdSql = New SqlCommand(SQL, oConnSql)
paraWC = New SqlParameter("#WC", SqlDbType.VarChar, 5)
paraWC.Value = lblWC.Text
oCmdSql.Parameters.Add(paraWC)
oCmdSql.CommandTimeout = 7200
Try
If oConnSql.State = ConnectionState.Closed Then
oConnSql.Open()
End If
' Adapter and Dataset
oAdptSql.SelectCommand = oCmdSql
oAdptSql.Fill(oDS, "dtList")
oAdptSql.Fill(dt)
If dt.Rows.Count > 0 Then
Dim ProgessQty, WIPQty, WOQuantity As String
Dim AgingWC, WOAging As Double
'Dim WCAge, WoAge As TimeSpan
Dim LeadTime As Double
Dim Holiday As Integer
Dim counter As Integer = 1
Dim count As Integer = dt.Rows.Count - 1
For i = 0 To count - 1
ProgessQty = GETProgressWOQuantity(Trim(dt.Rows(i)(0).ToString))
WOQuantity = Trim(dt.Rows(i)(1).ToString)
WIPQty = CInt(ProgessQty)
LeadTime = GetLeadTime(Trim(dt.Rows(i)(2).ToString), lblWC.Text)
Holiday = CheckForHolidays(CDate(dt.Rows(i)(4).ToString), Now())
WOAging = Format((DateDiff(DateInterval.Minute, CDate(dt.Rows(i)(4).ToString), Now())) / 60 / 24, "0.0") - Holiday
AgingWC = WOAging - LeadTime
If AgingWC >= 5 And WIPQty > 0 Then
TempDT.Rows.Add(Trim(dt.Rows(i)(0).ToString), WOQuantity, Trim(dt.Rows(i)(2).ToString), Trim(dt.Rows(i)(3).ToString), WIPQty, Trim(dt.Rows(i)(5).ToString), Math.Round(CDbl(WOAging), 2), Math.Round(CDbl(AgingWC), 2), IIf(Math.Round(CDbl(AgingWC), 2) >= WCLimit, "Red", "Black"))
'
counter += 1
Else
End If
Next
Dim dataView As New DataView(TempDT)
dataView.Sort = " AGINGATWC DESC"
SortDT = dataView.ToTable()
For j = 0 To SortDT.Rows.Count - 1
myArray = myArray & "|" & j + 1
myArray1 = myArray1 & "|" & Trim(SortDT.Rows(j)(0).ToString) 'WO
myArray2 = myArray2 & "|" & Trim(SortDT.Rows(j)(1).ToString) 'WO QTY
myArray3 = myArray3 & "|" & Trim(SortDT.Rows(j)(2).ToString) 'Part Number
myArray4 = myArray4 & "|" & Trim(SortDT.Rows(j)(3).ToString) 'Description
myArray5 = myArray5 & "|" & Trim(SortDT.Rows(j)(4).ToString) 'WIP QTY
myArray6 = myArray6 & "|" & Trim(SortDT.Rows(j)(5).ToString) 'WIP DAYS
myArray7 = myArray7 & "|" & Trim(SortDT.Rows(j)(6).ToString) 'WO Aging
myArray8 = myArray8 & "|" & Trim(SortDT.Rows(j)(7).ToString) 'Aging at WC
myArray9 = myArray9 & "|" & Trim(SortDT.Rows(j)(8).ToString) 'Color
myArray10 = myArray10 & "|" & Trim(SortDT.Rows(j)(5).ToString) 'WONOTE
Next
dt.Clear()
dt.Dispose()
oCmdSql.Dispose()
oConnSql.Close()
ViewState.Clear()
ViewState("JArray") = myArray
ViewState("JArray1") = myArray1
ViewState("JArray2") = myArray2
ViewState("JArray3") = myArray3
ViewState("JArray4") = myArray4
ViewState("JArray5") = myArray5
'ViewState("JArray6") = myArray6
ViewState("JArray7") = myArray7
ViewState("JArray8") = myArray8
ViewState("JArray9") = myArray9
ViewState("JArray10") = myArray10
End If
Catch ex As Exception
lblResult.Text = "Exception Message: " + ex.Message
Finally
End Try
End Sub
Now I realised if I run in Internet Explorer with varchar(max) it says

Import CSV and force all fields to Text format

I am importing a series of CSV files into Access tables. I have the following line that imports each file:
DoCmd.TransferText acImportDelim, , FN, F.Path, True
This import statement works and creates the necessary table. However, it creates the field types from the data, and depending on the first few rows of the data it may create a field as numeric that should be text - and then causes an error when it encounters a text value later in the file.
How can I force the field type to Text for every field in the input file? I've used Import Specifications before, but first the file format (provided by others outside my control) may change from time to time, and second it's a very "wide" file with 200+ column, so this isn't a practical answer.
This is not a great workaround, but I had to go through the process anyway to get around the 255 field limit in tables. In short, the import steps I ended up with are
Read the 1st line of the file as an inputstream
Split the line to get the field names, put them in a data dictionary table and then manually mark the ones I want to import
Use CREATE TABLE to create a new data table (selected fields only) with all of the fields set to TEXT
Read each line of the file as an inputstream
Split the line to get the data for each field
Use INSERT INTO to add the selected fields to the data table
Cumbersome, but it solves both problems - I'm not limited to 255 fields in the input files and I can control the data type of the fields as I create them.
The code, if anyone cares, is
Function Layout()
Set db = CurrentDb()
Folder = DLookup("[data folder]", "folder")
Dim FSO As New FileSystemObject
Set flist = FSO.GetFolder(Folder).Files
db.Execute ("delete * from [data dictionary]")
For Each F In flist
FN = Left(F.Name, InStr(F.Name, ".") - 1)
FT = Mid(F.Name, InStr(F.Name, ".") + 1)
If FT <> "csv" Then GoTo Skip
If TestFile(F.path) = "ASCII" Then
Set instream = FSO.OpenTextFile(F.path, ForReading, , 0)
Else: Set instream = FSO.OpenTextFile(F.path, ForReading, , -1)
End If
header = instream.ReadLine
Data = Split(header, ",")
For i = LBound(Data) To UBound(Data)
SQL = "insert into [data dictionary] ([table], [field], [index]) select "
SQL = SQL & "'" & FN & "','" & Data(i) & "','" & i & "'"
db.Execute SQL
Next i
Skip: Next F
End Function
Function TestFile(ByVal path As String)
Dim buffer As String
Dim InFileNum As Integer
Dim firstByte As Integer
Dim secondByte As Integer
Dim thirdByte As Integer
buffer = String(100, " ")
InFileNum = FreeFile
Open path For Binary Access Read As InFileNum
Get InFileNum, , buffer
Close InFileNum
firstByte = Asc(Mid(buffer, 1, 1))
secondByte = Asc(Mid(buffer, 2, 1))
thirdByte = Asc(Mid(buffer, 3, 1))
If (firstByte = 255 And secondByte = 254) Then
TestFile = "Unicode"
ElseIf (firstByte = 254 And secondByte = 255) Then
TestFile = "Unicode"
ElseIf (firstByte = 239 And secondByte = 187 And thirdByte = 191) Then
TestFile = "Unicode"
Else
TestFile = "ASCII"
End If
End Function
Function import()
Folder = DLookup("[data folder]", "folder")
Set db = CurrentDb()
Dim FSO As New FileSystemObject
Set Tlist = db.OpenRecordset("select [table] from [data dictionary] where ([required]<>'') group by [table]")
Tlist.MoveFirst
Do While Not Tlist.EOF
TN = Tlist.Fields("table").Value
Delete_table (TN)
Set flist = db.OpenRecordset("select * from [data dictionary] where [required]<>'' and [table]='" & TN & "'")
flist.MoveFirst
Text = ""
Do While Not flist.EOF
FN = flist.Fields("Field")
Text = Text & "," & FN & " " & IIf(InStr(FN, "Date") > 0 Or InStr(FN, "_DT") > 0, "DATETIME", "TEXT")
flist.MoveNext
Loop
SQL = "CREATE TABLE " & TN & "(" & Mid(Text, 2) & ")"
db.Execute SQL
path = Folder & "\" & TN & ".csv"
If TestFile(path) = "ASCII" Then
Set instream = FSO.OpenTextFile(path, ForReading, , 0)
Else: Set instream = FSO.OpenTextFile(path, ForReading, , -1)
End If
header = instream.ReadLine
Do While Not instream.AtEndOfStream
Line = parser(instream.ReadLine)
Data = Split(Line, ",")
flist.MoveFirst
Text = ""
Do While Not flist.EOF
n = flist.Fields("index").Value
Text = Text & ",'" & Data(n) & "'"
flist.MoveNext
Loop
SQL = "insert into [" & TN & "] values(" & Mid(Text, 2) & ")"
db.Execute SQL
Loop
Tlist.MoveNext
Loop
x = MultipleCodes()
MsgBox ("done")
End Function
Function parser(S)
parser = S
i = InStr(S, Chr(34))
If i = 0 Then
parser = S
Else
j = InStr(i + 1, S, Chr(34))
T = Mid(S, i + 1, j - i - 1)
T = Replace(T, ",", ";")
parser = Left(S, i - 1) & T & parser(Mid(S, j + 1))
End If
End Function

Having trouble with a image uploader on an ASP website

I have an image uploader built into a site for properties and it was working fine and now whenever i use the image uploader it gives me a 500 internal server error message.
My error log looks like this, does anyone know how to make sense of what its telling me?
ERROR LOG FILE -
https://pastebin.com/QtenvubM
CODE FOR UPLOADER:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!--#include virtual="/connection_includes/prop_search_conn_str.asp" -->
<%
Fkey = request.QueryString("Fkey")
property_ID = request.QueryString("property_ID")
uploadpath = "/palm_group/property_images/prop_no_" & property_ID
'------------------------------------------------------------
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If fs.FolderExists(server.MapPath(uploadpath)) = true Then
folder_exists = "yes"
Else
folder_exists = "no"
End If
'response.write uploadpath
'response.write folder_exists
'response.write server.MapPath(uploadpath)
'------------------------------------------------------------
if folder_exists = "no" then
fs.createfolder(server.MapPath(uploadpath))
end if
'-------------------------------------------------------------
Sub ImageUpload()
Server.ScriptTimeout = 555 '[Two Minute Timeout (this will allow upto 2 minutes of activity before ending)]
Set Upload = Server.CreateObject("Persits.Upload")
Count = Upload.Save(Server.MapPath(uploadpath))
For Each File in Upload.Files
LOCAL_LOC = File.Path
REMOTE_LOC = RootDir & replace(file.path, Server.mappath(uploadpath) + "\", "")
FILE_SIZE = File.Size
session("file") = File.filename
Next
Set Upload = Nothing
End Sub
'-------------------------------------------------------------
Call ImageUpload()
'-------------------------------------------------------------
if session("file") = "" then
set fname=nothing
set fs=nothing
response.redirect "/CMS_ADMIN_FILES/edit_property.asp?error=nofile&unique_ID=" & property_ID & "&Fkey=" & Fkey
end if
'-------------------------------------------------------------
file_extension = lcase(right(session("file"),4))
file_is_image = "false"
if file_extension = "jpeg" then file_extension = ".jpg"
if file_extension = ".jpg" then file_is_image = "true"
if file_extension = ".png" then file_is_image = "true"
if file_extension = ".gif" then file_is_image = "true"
if file_is_image <> "true" then
If fs.FileExists(server.MapPath(uploadpath & "\" & session("file"))) = true Then
fs.DeleteFile(server.MapPath(uploadpath & "\" & session("file")))
end if
set fname=nothing
set fs=nothing
response.redirect "/CMS_ADMIN_FILES/edit_property.asp?error=notimage&unique_ID=" & property_ID & "&Fkey=" & Fkey
else
' response.write file_extension
' response.write "<br>"
' response.write server.MapPath(uploadpath & "\" & session("file"))
if instr(session("file"),",") then response.Redirect "/CMS_ADMIN_FILES/edit_property.asp?error=illegalchar&unique_ID=" & property_ID & "&Fkey=" & Fkey
old_file = server.MapPath(uploadpath & "\" & session("file"))
file_counter = 1
stop_this_loop = "go"
session.Contents.Remove("file")
do while stop_this_loop = "go"
if file_counter < 10 then
new_file = "0" & file_counter & file_extension
else
new_file = file_counter & file_extension
end if
response.write "<br>" & new_file
If fs.FileExists(server.MapPath(uploadpath & "\" & new_file)) = true Then
file_counter = file_counter + 1
else
stop_this_loop = "stop"
end if
if file_counter < 10 then
new_file = "0" & file_counter & file_extension
else
new_file = file_counter & file_extension
end if
loop
fs.CopyFile old_file,server.MapPath(uploadpath & "\" & new_file)
fs.DeleteFile(old_file)
end if
set fname=nothing
set fs=nothing
' GET THE LAST LARGEST IMAGE ORDER NUMBER AND ADD ONE TO IT
Set order_images = Server.CreateObject("ADODB.Recordset")
order_images.ActiveConnection = CONN_property_search_images
order_images.Source = "SELECT TOP 1 img_order FROM property_images WHERE img_property_ID='" & session("ID") & "' ORDER BY img_order DESC"
order_images.CursorType = 0
order_images.CursorLocation = 2
order_images.LockType = 2
order_images.Open()
if order_images.eof then
new_order_number = 1
else
new_order_number = order_images("img_order") + 1
end if
order_images.close
set order_images = nothing
' NOW STICK IT IN THE DATABASE AND HAVE DONE WITH IT
Set DBCmd_content = Server.CreateObject("ADODB.Command")
DBCmd_content.ActiveConnection = CONN_property_search_images
DBCmd_content.CommandText = "INSERT INTO property_images(img_decription,img_property_ID,img_url,img_order) VALUES('','" & property_ID & "','" & uploadpath & "/" & new_file & "','" & new_order_number & "')"
DBCmd_content.Execute
DBCmd_content.ActiveConnection.Close
response.Redirect "/CMS_ADMIN_FILES/edit_property.asp?action=addok&unique_ID=" & property_ID & "&Fkey=" & Fkey
%>
You need to check the registration of the Persits Upload DLL. See here:
Server object error 'ASP 0177 : 800401f3' Server.CreateObject Failed

Using VBscript to access all values in JSON data

I have to do some vbscript that handles a json formatted output from a webserver. I am using an old vbscript code snippet I have found called "aspJSON" - I think it is from www.aspjson.com but that site is no longer available.
I have this JSON file:
{
"VAT":12678967.543233,
"buyInfo":{
"maximumBuyAmount":100,
"minimumBuyAmount":1,
},
"prices":[{
"unitPrice":12.50
"specialOfferPrice":8.75,
"period":{
"endDate":"\/Date(928142400000+0200)\/",
"startDate":"\/Date(928142400000+0200)\/",
},
}],
}
With the aspJSON code I can get some of the values from the data. Theese two will work fine:
Msgbox oJSON.data("VAT")
MsgBox oJSON.data("buyInfo").item("maximumBuyAmount")
But I cant seem to acces the values of prices:
[{"unitPrice":12.50}]
and period:
[{"period":{"endDate":"xxx"}}]
How can I access these values?
This is the aspJSON code:
'Februari 2014 - Version 1.17 by Gerrit van Kuipers
Class aspJSON
Public data
Private p_JSONstring
private aj_in_string, aj_in_escape, aj_i_tmp, aj_char_tmp, aj_s_tmp, aj_line_tmp, aj_line, aj_lines, aj_currentlevel, aj_currentkey, aj_currentvalue, aj_newlabel, aj_XmlHttp, aj_RegExp, aj_colonfound
Private Sub Class_Initialize()
Set data = Collection()
Set aj_RegExp = new regexp
aj_RegExp.Pattern = "\s{0,}(\S{1}[\s,\S]*\S{1})\s{0,}"
aj_RegExp.Global = False
aj_RegExp.IgnoreCase = True
aj_RegExp.Multiline = True
End Sub
Private Sub Class_Terminate()
Set data = Nothing
Set aj_RegExp = Nothing
End Sub
Public Sub loadJSON(inputsource)
inputsource = aj_MultilineTrim(inputsource)
If Len(inputsource) = 0 Then Err.Raise 1, "loadJSON Error", "No data to load."
select case Left(inputsource, 1)
case "{", "["
case else
Set aj_XmlHttp = CreateObject("Msxml2.ServerXMLHTTP")
aj_XmlHttp.open "GET", inputsource, False
aj_XmlHttp.setRequestHeader "Content-Type", "text/json"
aj_XmlHttp.setRequestHeader "CharSet", "UTF-8"
aj_XmlHttp.Send
inputsource = aj_XmlHttp.responseText
set aj_XmlHttp = Nothing
end select
p_JSONstring = CleanUpJSONstring(inputsource)
aj_lines = Split(p_JSONstring, Chr(13) & Chr(10))
Dim level(99)
aj_currentlevel = 1
Set level(aj_currentlevel) = data
For Each aj_line In aj_lines
aj_currentkey = ""
aj_currentvalue = ""
If Instr(aj_line, ":") > 0 Then
aj_in_string = False
aj_in_escape = False
aj_colonfound = False
For aj_i_tmp = 1 To Len(aj_line)
If aj_in_escape Then
aj_in_escape = False
Else
Select Case Mid(aj_line, aj_i_tmp, 1)
Case """"
aj_in_string = Not aj_in_string
Case ":"
If Not aj_in_escape And Not aj_in_string Then
aj_currentkey = Left(aj_line, aj_i_tmp - 1)
aj_currentvalue = Mid(aj_line, aj_i_tmp + 1)
aj_colonfound = True
Exit For
End If
Case "\"
aj_in_escape = True
End Select
End If
Next
if aj_colonfound then
aj_currentkey = aj_Strip(aj_JSONDecode(aj_currentkey), """")
If Not level(aj_currentlevel).exists(aj_currentkey) Then level(aj_currentlevel).Add aj_currentkey, ""
end if
End If
If right(aj_line,1) = "{" Or right(aj_line,1) = "[" Then
If Len(aj_currentkey) = 0 Then aj_currentkey = level(aj_currentlevel).Count
Set level(aj_currentlevel).Item(aj_currentkey) = Collection()
Set level(aj_currentlevel + 1) = level(aj_currentlevel).Item(aj_currentkey)
aj_currentlevel = aj_currentlevel + 1
aj_currentkey = ""
ElseIf right(aj_line,1) = "}" Or right(aj_line,1) = "]" or right(aj_line,2) = "}," Or right(aj_line,2) = "]," Then
aj_currentlevel = aj_currentlevel - 1
ElseIf Len(Trim(aj_line)) > 0 Then
if Len(aj_currentvalue) = 0 Then aj_currentvalue = aj_line
aj_currentvalue = getJSONValue(aj_currentvalue)
If Len(aj_currentkey) = 0 Then aj_currentkey = level(aj_currentlevel).Count
level(aj_currentlevel).Item(aj_currentkey) = aj_currentvalue
End If
Next
End Sub
Public Function Collection()
set Collection = CreateObject("Scripting.Dictionary")
End Function
Public Function AddToCollection(dictobj)
if TypeName(dictobj) <> "Dictionary" then Err.Raise 1, "AddToCollection Error", "Not a collection."
aj_newlabel = dictobj.Count
dictobj.Add aj_newlabel, Collection()
set AddToCollection = dictobj.item(aj_newlabel)
end function
Private Function CleanUpJSONstring(aj_originalstring)
aj_originalstring = Replace(aj_originalstring, Chr(13) & Chr(10), "")
aj_originalstring = Mid(aj_originalstring, 2, Len(aj_originalstring) - 2)
aj_in_string = False : aj_in_escape = False : aj_s_tmp = ""
For aj_i_tmp = 1 To Len(aj_originalstring)
aj_char_tmp = Mid(aj_originalstring, aj_i_tmp, 1)
If aj_in_escape Then
aj_in_escape = False
aj_s_tmp = aj_s_tmp & aj_char_tmp
Else
Select Case aj_char_tmp
Case "\" : aj_s_tmp = aj_s_tmp & aj_char_tmp : aj_in_escape = True
Case """" : aj_s_tmp = aj_s_tmp & aj_char_tmp : aj_in_string = Not aj_in_string
Case "{", "["
aj_s_tmp = aj_s_tmp & aj_char_tmp & aj_InlineIf(aj_in_string, "", Chr(13) & Chr(10))
Case "}", "]"
aj_s_tmp = aj_s_tmp & aj_InlineIf(aj_in_string, "", Chr(13) & Chr(10)) & aj_char_tmp
Case "," : aj_s_tmp = aj_s_tmp & aj_char_tmp & aj_InlineIf(aj_in_string, "", Chr(13) & Chr(10))
Case Else : aj_s_tmp = aj_s_tmp & aj_char_tmp
End Select
End If
Next
CleanUpJSONstring = ""
aj_s_tmp = split(aj_s_tmp, Chr(13) & Chr(10))
For Each aj_line_tmp In aj_s_tmp
aj_line_tmp = replace(replace(aj_line_tmp, chr(10), ""), chr(13), "")
CleanUpJSONstring = CleanUpJSONstring & aj_Trim(aj_line_tmp) & Chr(13) & Chr(10)
Next
End Function
Private Function getJSONValue(ByVal val)
val = Trim(val)
If Left(val,1) = ":" Then val = Mid(val, 2)
If Right(val,1) = "," Then val = Left(val, Len(val) - 1)
val = Trim(val)
Select Case val
Case "true" : getJSONValue = True
Case "false" : getJSONValue = False
Case "null" : getJSONValue = Null
Case Else
If (Instr(val, """") = 0) Then
If IsNumeric(val) Then
getJSONValue = CDbl(val)
Else
getJSONValue = val
End If
Else
If Left(val,1) = """" Then val = Mid(val, 2)
If Right(val,1) = """" Then val = Left(val, Len(val) - 1)
getJSONValue = aj_JSONDecode(Trim(val))
End If
End Select
End Function
Private JSONoutput_level
Public Function JSONoutput()
dim wrap_dicttype, aj_label
JSONoutput_level = 1
wrap_dicttype = "[]"
For Each aj_label In data
If Not aj_IsInt(aj_label) Then wrap_dicttype = "{}"
Next
JSONoutput = Left(wrap_dicttype, 1) & Chr(13) & Chr(10) & GetDict(data) & Right(wrap_dicttype, 1)
End Function
Private Function GetDict(objDict)
dim aj_item, aj_keyvals, aj_label, aj_dicttype
For Each aj_item In objDict
Select Case TypeName(objDict.Item(aj_item))
Case "Dictionary"
GetDict = GetDict & Space(JSONoutput_level * 4)
aj_dicttype = "[]"
For Each aj_label In objDict.Item(aj_item).Keys
If Not aj_IsInt(aj_label) Then aj_dicttype = "{}"
Next
If aj_IsInt(aj_item) Then
GetDict = GetDict & (Left(aj_dicttype,1) & Chr(13) & Chr(10))
Else
GetDict = GetDict & ("""" & aj_JSONEncode(aj_item) & """" & ": " & Left(aj_dicttype,1) & Chr(13) & Chr(10))
End If
JSONoutput_level = JSONoutput_level + 1
aj_keyvals = objDict.Keys
GetDict = GetDict & (GetSubDict(objDict.Item(aj_item)) & Space(JSONoutput_level * 4) & Right(aj_dicttype,1) & aj_InlineIf(aj_item = aj_keyvals(objDict.Count - 1),"" , ",") & Chr(13) & Chr(10))
Case Else
aj_keyvals = objDict.Keys
GetDict = GetDict & (Space(JSONoutput_level * 4) & aj_InlineIf(aj_IsInt(aj_item), "", """" & aj_JSONEncode(aj_item) & """: ") & WriteValue(objDict.Item(aj_item)) & aj_InlineIf(aj_item = aj_keyvals(objDict.Count - 1),"" , ",") & Chr(13) & Chr(10))
End Select
Next
End Function
Private Function aj_IsInt(val)
aj_IsInt = (TypeName(val) = "Integer" Or TypeName(val) = "Long")
End Function
Private Function GetSubDict(objSubDict)
GetSubDict = GetDict(objSubDict)
JSONoutput_level= JSONoutput_level -1
End Function
Private Function WriteValue(ByVal val)
Select Case TypeName(val)
Case "Double", "Integer", "Long": WriteValue = val
Case "Null" : WriteValue = "null"
Case "Boolean" : WriteValue = aj_InlineIf(val, "true", "false")
Case Else : WriteValue = """" & aj_JSONEncode(val) & """"
End Select
End Function
Private Function aj_JSONEncode(ByVal val)
val = Replace(val, "\", "\\")
val = Replace(val, """", "\""")
'val = Replace(val, "/", "\/")
val = Replace(val, Chr(8), "\b")
val = Replace(val, Chr(12), "\f")
val = Replace(val, Chr(10), "\n")
val = Replace(val, Chr(13), "\r")
val = Replace(val, Chr(9), "\t")
aj_JSONEncode = Trim(val)
End Function
Private Function aj_JSONDecode(ByVal val)
val = Replace(val, "\""", """")
val = Replace(val, "\\", "\")
val = Replace(val, "\/", "/")
val = Replace(val, "\b", Chr(8))
val = Replace(val, "\f", Chr(12))
val = Replace(val, "\n", Chr(10))
val = Replace(val, "\r", Chr(13))
val = Replace(val, "\t", Chr(9))
aj_JSONDecode = Trim(val)
End Function
Private Function aj_InlineIf(condition, returntrue, returnfalse)
If condition Then aj_InlineIf = returntrue Else aj_InlineIf = returnfalse
End Function
Private Function aj_Strip(ByVal val, stripper)
If Left(val, 1) = stripper Then val = Mid(val, 2)
If Right(val, 1) = stripper Then val = Left(val, Len(val) - 1)
aj_Strip = val
End Function
Private Function aj_MultilineTrim(TextData)
aj_MultilineTrim = aj_RegExp.Replace(TextData, "$1")
End Function
private function aj_Trim(val)
aj_Trim = Trim(val)
Do While Left(aj_Trim, 1) = Chr(9) : aj_Trim = Mid(aj_Trim, 2) : Loop
Do While Right(aj_Trim, 1) = Chr(9) : aj_Trim = Left(aj_Trim, Len(aj_Trim) - 1) : Loop
aj_Trim = Trim(aj_Trim)
end function
End Class
Unlike VAT and buyInfo, prices is a Collection which can contain multiple instances (notice the difference in the JSON structure, prices is encapsulated by square brackets). Whenever you deal with Collections a loop is required to iterate through the instances to get at their underlying properties.
I'd recommend a For Each loop, like below. #
Dim key, price
'Iterating a Scripting.Dictionary using For Each returns the key.
For Each key In oJSON.data("prices")
'Get the price instance by passing the key back into
'the Scripting.Dictionary.
Set price = oJSON.data("prices")(key)
MsgBox price.item("unitPrice")
MsgBox price.item("specialOfferPrice")
MsgBox price.item("period").item("endDate")
MsgBox price.item("period").item("startDate")
'Clear object before iterating the next instance.
Set price = Nothing
Next
# Code provided untested
Looking into this a bit more with some useful discussion with #omegastripes in the comments and looking through the aspJSON class, you should be able to access the Collection / Array items by ordinal, for example to get unitPrice you would use;
oJSON("prices")(0).Item("unitPrice")
With this in mind did a quick test script and here is the result.
Option Explicit
Dim prices: Set prices = CreateObject("Scripting.Dictionary")
Dim price, period
With prices
Set price = CreateObject("Scripting.Dictionary")
With price
Call .Add("unitPrice", 12.50)
Call .Add("specialOfferPrice", 8.75)
Set period = CreateObject("Scripting.Dictionary")
With period
Call .Add("endDate", "/Date(928142400000+0200)/")
End With
Call .Add("period", period)
End With
'Uses same method as the AddToCollection() in aspJSON to
'assign the ordinal position when adding the child Dictionary.
Call .Add(.Count, price)
End With
WScript.Echo prices(0).Item("unitPrice")
WScript.Echo prices(0).Item("period").Item("endDate")
Output:
12.5
/Date(928142400000+0200)/

Access-VBA: How do I detect the mouse-key in a TreeView-NodeClick

I have a TreeView with a Click-Event. Since I need to implement a node-oriented dropdown-context-menu by right-click, how may I check in the existing Click-Event if the right mouse-butten was pressed. My Methode so far, looks like this:
Private Sub tvwKategorien_NodeClick(ByVal Node As Object)
Dim sBez1 As String
Dim sLangtext As String
Dim sWKZ As String
Dim sSprache As String
Dim dPreis As Double
If ((Node Is Nothing) = False) Then
If mbParseNodeKeyAndTag(Node) Then
Set moSelectedNode = Node
If msKategorie = frmArtikelgruppenRoot Then
Me.pagKategorie.Visible = False
Me.pagArtikel.Visible = False
Me.pagPicture.Visible = False
Me.pagCrosslinks.Visible = False
Me.SubArtikel.Visible = False
Me.txtKategorie = msKategorie
Me.txtBezeichnung = msBezeichnung
Me.PicArtikel.Visible = False
Call mEnableSubArtikel
Else
If mbIstNodeKategorie(moSelectedNode) Then
Me.pagKategorie.Visible = True
Me.pagArtikel.Visible = False
Me.pagPicture.Visible = False
Me.pagCrosslinks.Visible = False
Me.SubArtikel.Visible = True
Me.txtKategorie = msKategorie
Me.txtBezeichnung = msBezeichnung
Me.PicArtikel.Visible = False
If Node.Child Is Nothing Then
Dim oNodeParam As Node
Set oNodeParam = Node
Call mReadUntergruppen(oNodeParam, oNodeParam.Key, gnCInt(gsParameter(oNodeParam.Text, "Gruppenebene")) + 1)
End If
Call mEnableSubArtikel
Dim rs As Recordset
Set rs = Me.SubArtikel.Form.Recordset
If Not rs Is Nothing Then
Call mReadArtikel(Node, Node.Key, gnCInt(gsParameter(Node.Text, "Gruppenebene")) + 1)
Node.Expanded = True
Else
Node.Expanded = False
End If
Else
Me.pagKategorie.Visible = False
Me.pagArtikel.Visible = True
Me.pagPicture.Visible = True
Me.pagCrosslinks.Visible = True
Me.SubArtikel.Visible = False
Me.txtArtNr = msBezeichnung
Me.txtArt = msBezeichnung & " " & gvntLookup("Matchcode", "KHKArtikel", "Artikelnummer='" & msBezeichnung & "' AND Mandant=" & gnManId, "")
cbBild.Value = "ITPWeb_"
Call mInitPicture
nil = gITPWebGetArtPreis(msBezeichnung, 0, sWKZ, dPreis, cbShop.Value)
Me.txtArtPreis = dPreis
Me.txtArtWkz = sWKZ
If gvntNull2Arg(cboSprache, "") = "" Then
sSprache = "W" & gvntManProperty(22)
Else
sSprache = CStr(cboSprache)
End If
nil = gITPWebGetArtBez(sSprache, msBezeichnung, sBez1, sLangtext)
Me.txtArtBezeichnung = sBez1
Me.txtArtLangtext = sLangtext
msAktuelleKategorie = Split(Node.Key, ";")(0)
Me.cboBonusprodukt.Locked = False
sSplit = Split(Node.Key, ";")
Me.cboBonusprodukt.Value = gvntLookup("BonusProduct", "ITPWebKategorienArtikel", "Artikelnummer=" & gsStr2Sql(msBezeichnung) & " AND Mandant=" & gnManId & " and Kategorie = " & gsStr2Sql(msAktuelleKategorie) & " and Pos = " & sSplit(getArrayLenght(sSplit)), 0)
Me.cboBonusprodukt.AllowValueListEdits = False
Me.txtBonuspunkte = gvntNull2Arg(gvntLookup("Bonuspunkte", "ITPWebKategorienArtikel", "Artikelnummer=" & gsStr2Sql(msBezeichnung) & " AND Mandant=" & gnManId & " and Kategorie = " & gsStr2Sql(msAktuelleKategorie) & " and Pos = " & sSplit(getArrayLenght(sSplit)), 0), 0)
Me.chkOrderable = gvntLookup("USER_ITPWebOrderable", "KHKArtikel", "Artikelnummer=" & gsStr2Sql(msBezeichnung) & " AND Mandant=" & gnManId, -1)
Me.chkShopActive = gvntLookup("USER_ITPWebShopActive", "KHKArtikel", "Artikelnummer=" & gsStr2Sql(msBezeichnung) & " AND Mandant=" & gnManId, -1)
Me.chkPricePush = gvntLookup("USER_ITPWebPricePush", "KHKArtikel", "Artikelnummer=" & gsStr2Sql(msBezeichnung) & " AND Mandant=" & gnManId, 0)
Call mEnableSubCrosslinks
End If
End If
End If
End If
tvwKategorien_NodeClick_Error:
End Sub
I'm working inside an access-document with VBA :(
You have to use MouseDown event for your tree tvwKategorienand flag some module variable in order to check later it in NodeClick
put this at the beginning of the Module but after Option strings
private MouseButton as Integer
Add MouseDown event
Private Sub tvwKategorien_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal x As Long, ByVal y As Long)
MouseButton =Button
End Sub
Then use such condition to detect right click in your existing NodeClick event
If MouseButton = acRightButton Then ' right
and
If MouseButton = acLeftButton Then ' left